local C = Broker_Everything.color
local location_onupdate_interval = 1
local tip = LibStub("tektip-1.0").new(3, "LEFT", "LEFT", "RIGHT")
local zoneColor
local worldLoc = " "

local function updateZone()
	local subZone = GetSubZoneText() or ""
	local zone = GetRealZoneText() or ""
	local p, _, f = GetZonePVPInfo()


	if p == "combat" or p == "arena" or p == "hostile" then
		zoneColor = "red"
	elseif p == "contested" or p == "sanctuary"  or p == nil then
		zoneColor = "yellow"
	elseif p == "friendly" then
		zoneColor = "green"
	end

	if subZone == nil  or subZone == "" then
		return zone
	else
		return subZone
	end


end

local function updateLocation()
	local location = ""
	local x, y = GetPlayerMapPosition("player")

	if x ~= 0 and y ~= 0 then
		location = string.format("(%.0f, %.0f)", x * 100, y * 100)
	end

	return location
end



local zonetext_onevent = function (self, event)
	local displayLine

	if (event == "PLAYER_LOGIN") or (event == "ZONE_CHANGED") or (event == "ZONE_CHANGED_INDOORS") or (event == "ZONE_CHANGED_NEW_AREA") or (event == "PLAYER_ENTERING_WORLD") or (event == "ADDON_LOADED") then
		worldLoc = updateZone()
	end

	if zoneColor == "red" then
		displayLine = C.red(worldLoc .. " " .. updateLocation())
	elseif zoneColor == "yellow" then
		displayLine = C.yellow(worldLoc.. " " .. updateLocation())
	elseif zoneColor == "green" then
		displayLine = C.green(worldLoc .. " " .. updateLocation())
	else  displayLine = C.white(worldLoc .. " " .. updateLocation())
	end

	self.obj.text = displayLine
end


local zonetext_events = {
	"PLAYER_LOGIN",
	"ZONE_CHANGED",
	"ZONE_CHANGED_INDOORS",
	"ZONE_CHANGED_NEW_AREA",
	"PLAYER_ENTERING_WORLD",
	"ADDON_LOADED"
}


local zone_init = function(obj)
	if not obj then return end

	obj = obj.obj

	obj.OnLeave = function()
		tip:Hide()
	end

	obj.OnEnter = function(self)
		tip:AnchorTo(self)
		
		tip:AddLine(C.white("Location Information"))
		tip:AddMultiLine(C.yellow("Zone:"), " ", C.white(GetRealZoneText()))
		tip:AddMultiLine(C.yellow("Sub-Zone:"), " " , C.white(GetSubZoneText()))
		tip:AddLine(" ")
		tip:AddLine(C.white("Home Location"))
		tip:AddMultiLine(C.yellow("Inn:"), " ", C.white(GetBindLocation()))
		tip:Show()
	end
end

local zonetext_onupdate = function(self)
	local displayLine = updateLocation()
	self.obj.text = displayLine
end


local zonetext_onclick = function()
	if GUILockDown == nil then 
		ToggleFrame(WorldMapFrame)
	elseif GUILockDown == 1 then 
		return 
	end
end



Broker_Everything:Register("ZoneText",
	GetItemIcon(11105),
	zone_init,
	zonetext_onevent,
	zonetext_events,
	zonetext_onclick,
	0, -- zonetext_tooltip,
	zonetext_onevent,
	location_onupdate_interval)
