local GetGameTime = GetGameTime
local clock_update_interval = 4
local C = Broker_Everything.color


local clock_init = function()
	if not Broker_EverythingDB.clock_display then
		Broker_EverythingDB.clock_local = 0
		Broker_EverythingDB.clock_display = 0
	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.clock_local == 0 then
		h, m = GetGameTime()
		if Broker_EverythingDB.clock_display == 0 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.clock_display == 0 then
			dataobj.text = date("%H:%M")
		else
			-- produces 'date' format too long error
			--self.obj.text = date("%l:%M %p")
			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["CLOCKHINTLEFT"]))
	t:AddLine(C.dkgreen(L["CLOCKHINTRIGHT"]))
	t:AddLine(C.dkgreen(L["CLOCKSHIFTRIGHT"]))
	t:AddLine(C.dkgreen(L["CLOCKSHIFTLEFT"]))
end


local clock_onclick = function(self, btn)
	local shift = IsShiftKeyDown()
	if btn == "RightButton" and not shift then
		if Broker_EverythingDB.clock_local == 1 then
			Broker_EverythingDB.clock_local = 0
		else
			Broker_EverythingDB.clock_local = 1
		end
		clock_onupdate(self)
	elseif btn == "RightButton" and shift then
		ToggleCalendar()
	elseif btn == "LeftButton" and shift then 
		if Broker_EverythingDB.clock_display == 1 then
			Broker_EverythingDB.clock_display = 0
		else
			Broker_EverythingDB.clock_display = 1
		end
		clock_onupdate(self)
	else
		ToggleTimeManager()
	end
end


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

