-- local Image = require "widgets/image"
local Widget = require "widgets/widget"
local GestureBadge = require("widgets/gesturebadge")

-- local ATLAS = "images/avatars.xml"

local GestureWheel = Class(Widget, function(self, emotes, image, text)
    Widget._ctor(self, "GestureWheel")
    self.isFE = false
    self:SetClickable(false)

    self.root = self:AddChild(Widget("root"))
    -- self.root:SetScaleMode(SCALEMODE_PROPORTIONAL)

    self.icon = self.root:AddChild(Widget("target"))
    self.icon:SetScale(1)
	
	self.gestures = {}
	local count = 0
	for k,v in pairs(emotes) do count = count + 1 end
	local dist = (65*count)/(math.pi)
	local delta = 2*math.pi/count
	local theta = 0
	for k,v in pairs(emotes) do
		self.gestures[k] = self.icon:AddChild(GestureBadge(ThePlayer.prefab, k, v, image, text))
		-- print(k)
		-- print("Positioning:", dist*math.cos(theta),0,dist*math.sin(theta))
		self.gestures[k]:SetPosition(dist*math.cos(theta),dist*math.sin(theta), 0)
		theta = theta + delta
	end
	-- self.gesture = self.icon:AddChild(GestureBadge("waxwell"))
	-- self.gesture:SetPosition(-100, 0, 0)
	
    -- self.headbg = self.icon:AddChild(Image(ATLAS, "avatar_bg.tex"))
    -- self.head = self.icon:AddChild(Image(ATLAS, "waxwell"))
    -- self.headframe = self.icon:AddChild(Image(ATLAS, "avatar_frame_white.tex"))
end)

local function GetMouseDistance(self, gesture, mouse)
	local pos = self:GetPosition()
	if gesture ~= nil then
		local offset = gesture:GetPosition()
		pos.x = pos.x + offset.x
		pos.y = pos.y + offset.y
	end
	local dx = pos.x - mouse.x
	local dy = pos.y - mouse.y
	return dx*dx + dy*dy
end

function GestureWheel:OnUpdate()
	--find the gesture closest to the mouse
	local mouse = TheInput:GetScreenPosition()
	local mindist = 100000000
	local mingesture = nil
	for k,v in pairs(self.gestures) do
		local dist = GetMouseDistance(self, v, mouse)
		if dist < mindist then
			mindist = dist
			mingesture = k
		end
	end
	-- make sure the mouse isn't still close to the center of the gesture wheel
	if GetMouseDistance(self, nil, mouse) < mindist then
		mingesture = nil
		self.activegesture = nil
	end
	
	for k,v in pairs(self.gestures) do
		if k == mingesture then
			v:Expand()
			self.activegesture = k
		else
			v:Contract()
		end
	end
end

return GestureWheel