local addon, ns = ...
local C = ns.shared.color
local L = ns.L

local GetGameTime = GetGameTime
local clock_update_interval = 4


local clock_init = function()
	if Broker_EverythingDB[L["Clock"]].enabled == nil then
		Broker_EverythingDB[L["Clock"]] = {
			enabled = true,
			timeLocal = true,
			format24 = true,
		}
	elseif Broker_EverythingDB[L["Clock"]].format24 == nil then
		Broker_EverythingDB[L["Clock"]].timeLocal = true
		Broker_EverythingDB[L["Clock"]].format24 = true
	end

			
end

local clock_onupdate = function(self)
	local h, m
	local dataobj = self.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["Clock"])

	if Broker_EverythingDB[L["Clock"]].timeLocal == false then
		h, m = GetGameTime()
		if Broker_EverythingDB[L["Clock"]].format24 == true then
			dataobj.text = string.format ("%02d:%02d", h, m)
		else
			local a = "AM"
			if h >= 12 then
				h = h - 12
				a = "PM"
			end
			if h == 0 then h = 12 end
			dataobj.text = string.format ("%02d:%02d %s", h, m, a)
		end
	else
		if Broker_EverythingDB[L["Clock"]].format24 == true then
			dataobj.text = date("%H:%M")
		else
			dataobj.text = date("%I:%M %p")
		end
	end
end


local clock_tooltip = function(t)
	local h, m = GetGameTime()

	t:AddLine(L["Clock"])
	t:AddLine(" ")
	t:AddDoubleLine(C.white(L["Server Time"]), C.white(string.format ("%02d:%02d", h, m)))
	t:AddDoubleLine(C.white(L["Local Time"]), C.white(date("%H:%M")))
	t:AddLine(" ")
	t:AddLine(C.dkgreen(L["Hint: Left-click to open the Time manager."]))
	t:AddLine(C.dkgreen(L["Right-click to switch between local and server time."]))
	t:AddLine(C.dkgreen(L["Shift + Right-click to open calendar."]))
	t:AddLine(C.dkgreen(L["Shift + Left-click to switch between 12 & 24 hour time."]))
end


local clock_onclick = function(self, btn)
	local shift = IsShiftKeyDown()
	if btn == "RightButton" and not shift then
		if Broker_EverythingDB[L["Clock"]].timeLocal == true then
			Broker_EverythingDB[L["Clock"]].timeLocal = false
		else
			Broker_EverythingDB[L["Clock"]].timeLocal = true
		end
		clock_onupdate(self)
	elseif btn == "RightButton" and shift then
		ToggleCalendar()
	elseif btn == "LeftButton" and shift then 
		if Broker_EverythingDB[L["Clock"]].format24 == true then
			Broker_EverythingDB[L["Clock"]].format24 = false
		else
			Broker_EverythingDB[L["Clock"]].format24 = true
		end
		clock_onupdate(self)
	else
		ToggleTimeManager()
	end
end


Broker_Everything:Register(L["Clock"],
	"Interface\\Addons\\Broker_Everything\\media\\clock",
	clock_init,
	0,				-- clock_onevent
	0,				-- clock_events
	clock_onclick,
	clock_tooltip,
	clock_onupdate,
	clock_update_interval)

