local KEY_CTRL = GLOBAL.KEY_CTRL
local Vector3 = GLOBAL.Vector3
local TheInput = GLOBAL.TheInput
local table = GLOBAL.table
local require = GLOBAL.require
local unpack = GLOBAL.unpack

Assets = {
	Asset( "IMAGE", "images/status_bg.tex"),
	Asset("ATLAS", "images/status_bg.xml"),
}

local ToggleButton = GetModConfigData("togglekey")
local center = GetModConfigData("center")
local imagetext = GetModConfigData("imagetext")
local image = imagetext > 1
local text = imagetext%2 == 1
-- local GestureBadge = require("widgets/gesturebadge")
local GestureWheel = require("widgets/gesturewheel")

local controls = nil
local keydown = false

local STARTSCALE = 0.25
local NORMSCALE = 1

local gesture = nil
local EMOTES = {
	wave = {anim={"emoteXL_waving1", "emoteXL_waving2"}, randomanim=true},
	bye = {anim={"emoteXL_waving4", "emoteXL_waving3"}, randomanim=true},
	happy = {anim="emoteXL_happycheer"},
	angry = {anim="emoteXL_angry"},
	sad = {anim="emoteXL_sad", fx="tears", fxoffset={0,-.8,0}, fxdelay=17*GLOBAL.FRAMES},
	annoyed = {anim="emoteXL_annoyed"},
	joy = {anim="research", fx=false},
	dance = {anim={"run_pre", "run_loop", "run_loop", "run_loop", "run_pst"}},
	bonesaw = {anim="emoteXL_bonesaw"},
	facepalm = {anim="emoteXL_facepalm"},
	--TODO: make sure this list is up to date
}

local function IsDefaultScreen()
	return GLOBAL.TheFrontEnd:GetActiveScreen().name:find("HUD") ~= nil
end

local function ShowGestureWheel()
	if keydown then return end
	keydown = true
	if not IsDefaultScreen() then return end
	
	if not center then
		controls.gesturewheel:SetPosition(TheInput:GetScreenPosition():Get())
	end
	controls.gesturewheel:Show()
	controls.gesturewheel:ScaleTo(STARTSCALE, NORMSCALE, .25)
end

local function HideGestureWheel()
	keydown = false
	controls.gesturewheel:Hide()
	controls.gesturewheel.inst.UITransform:SetScale(STARTSCALE, STARTSCALE, 1)
	if not IsDefaultScreen() then return end
	if controls.gesturewheel.activegesture then
		GLOBAL.TheNet:Say("/" .. controls.gesturewheel.activegesture, true)
	end
end


local function AddGestureWheel(self)
	controls = self -- this just makes controls available in the rest of the modmain's functions
	controls.gesturewheel = controls:AddChild(GestureWheel(EMOTES, image, text))
	local screenwidth, screenheight = GLOBAL.TheSim:GetScreenSize()
	controls.gesturewheel:SetPosition(screenwidth/2,screenheight/2,0)
	controls.gesturewheel.inst.UITransform:SetScale(STARTSCALE, STARTSCALE, 1)
	controls.gesturewheel:Hide()
	
	GLOBAL.TheInput:AddKeyDownHandler(ToggleButton, ShowGestureWheel)
	GLOBAL.TheInput:AddKeyUpHandler(ToggleButton, HideGestureWheel)
	
	local OldOnUpdate = controls.OnUpdate
	local function OnUpdate(...)
		OldOnUpdate(...)
		if keydown then
			self.gesturewheel:OnUpdate()
		end
	end
	controls.OnUpdate = OnUpdate
end
AddClassPostConstruct( "widgets/controls", AddGestureWheel )