local L = LibStub("AceLocale-3.0"):GetLocale("Broker_CTA")
local Broker_CTA = LibStub("LibDataBroker-1.1"):NewDataObject("Broker CallToArms", {type = "data source", label = "Broker CallToArms", icon = "Interface\\Icons\\inv_misc_bag_34.blp", text = L["Unavailable"]})
LibStub("AceTimer-3.0"):Embed(Broker_CTA)
LibStub("AceEvent-3.0"):Embed(Broker_CTA)

local CTA_RANDOM_DUNGEONS = {301, 341}


local TANK_ICON = "|TInterface\\LFGFRAME\\UI-LFG-ICON-PORTRAITROLES.blp:14:14:0:0:64:64:0:18:22:40|t"
local HEALER_ICON = "|TInterface\\LFGFRAME\\UI-LFG-ICON-PORTRAITROLES.blp:14:14:0:0:64:64:20:38:1:19|t"
local DPS_ICON = "|TInterface\\LFGFRAME\\UI-LFG-ICON-PORTRAITROLES.blp:14:14:0:0:64:64:20:38:22:40|t"

function Broker_CTA:RequestInfo()
	RequestLFDPlayerLockInfo()
end

function Broker_CTA:UpdateLDB()
	local tankReward = false
	local healerReward = false
	local dpsReward = false
	local unavailable = true
	for i = 1,GetNumRandomDungeons() do
		local id, name = GetLFGRandomDungeonInfo(i)
		for j = 1,LFG_ROLE_NUM_SHORTAGE_TYPES do
			local eligible, forTank, forHealer, forDamage, itemCount = GetLFGRoleShortageRewards(id, j)
			if eligible then unavailable = false end
			if not self.db.profile.hide.dungeons[tostring(id)] then
				if eligible and forTank and itemCount > 0 then tankReward = true end
				if eligible and forHealer and itemCount > 0 then healerReward = true end
				if eligible and forDamage and itemCount > 0 then dpsReward = true end
			end
		end
	end
	if unavailable then self.text = L["Unavailable"]
	else
		local ldbString = self:MakeIconString(tankReward, healerReward, dpsReward)
		if ldbString == "" then ldbString = L["None"] end
		self.text = ldbString
	end
end

function Broker_CTA:OnEnter()
	GameTooltip:SetOwner(self, "ANCHOR_NONE")
	GameTooltip:SetPoint("TOPLEFT", self, "BOTTOMLEFT")
	GameTooltip:ClearLines()
	GameTooltip:AddLine(L["Call To Arms"])
	GameTooltip:AddLine("")
	
	local allUnavailable = true
	local numCTA = 0
	local numShownCTA = 0
	for i = 1,GetNumRandomDungeons() do
		local id, name = GetLFGRandomDungeonInfo(i)
		local tankReward = false
		local healerReward = false
		local dpsReward = false
		local unavailable = true
		for j = 1,LFG_ROLE_NUM_SHORTAGE_TYPES do
			local eligible, forTank, forHealer, forDamage, itemCount = GetLFGRoleShortageRewards(id, j)
			if eligible then unavailable = false end
			if eligible and forTank and itemCount > 0 then tankReward = true end
			if eligible and forHealer and itemCount > 0 then healerReward = true end
			if eligible and forDamage and itemCount > 0 then dpsReward = true end
		end
		if not unavailable then
			allUnavailable = false
			local rolesString = Broker_CTA:MakeIconString(tankReward, healerReward, dpsReward, true)
			if rolesString ~= ""  then 
				if Broker_CTA.db.profile.showAllInTooltip or not Broker_CTA.db.profile.hide.dungeons[tostring(id)] then 
					GameTooltip:AddDoubleLine(name, rolesString)
					numShownCTA = numShownCTA + 1
				end
			end
			if tankReward or healerReward or dpsReward then numCTA = numCTA + 1 end
		end
	end
	if allUnavailable then GameTooltip:AddLine(L["Could not get Call To Arms information."])
	elseif numCTA == 0 then GameTooltip:AddLine(L["No dungeons are currently offering a Call To Arms."])
	elseif numShownCTA == 0 then GameTooltip:AddLine(L["All dungeons with Call To Arms are hidden based on your settings."]) end
	GameTooltip:Show()
end

Broker_CTA.OnLeave = GameTooltip_Hide

function Broker_CTA:OnClick(button, down)
	if button == "RightButton" then
		InterfaceOptionsFrame_OpenToCategory("Broker CallToArms")
	else
		ToggleLFDParentFrame()
	end

end

local defaults = {
	profile = {
		hide = {
			dungeons = {
			},
			roles = {
				tank = false,
				healer = false,
				damage = false
			}
		},
		icons = true,
		showAllInTooltip = false
	}
}

local optionsTable = {
	type = "group",
	name = "Broker CallToArms",
	args = {
		hideDungeons = {
			name = L["Hide these dungeons:"],
			type = "group",
			guiInline = true,
			args = {}
		},
		hideRoles = {
			name = L["Hide these roles:"],
			type = "group",
			guiInline = true,
			args = {
				tank = {
					name = L["Tank"],
					desc = nil,
					type = "toggle",
					get = function(info) return Broker_CTA.db.profile.hide.roles.tank end,
					set = function(info, val) Broker_CTA.db.profile.hide.roles.tank = val; Broker_CTA:UpdateLDB() end
				},
				healer = {
					name = L["Healer"],
					desc = nil,
					type = "toggle",
					get = function(info) return Broker_CTA.db.profile.hide.roles.healer end,
					set = function(info, val) Broker_CTA.db.profile.hide.roles.healer = val; Broker_CTA:UpdateLDB() end
				},
				damage = {
					name = L["Damage"],
					desc = nil,
					type = "toggle",
					get = function(info) return Broker_CTA.db.profile.hide.roles.damage end,
					set = function(info, val) Broker_CTA.db.profile.hide.roles.damage = val; Broker_CTA:UpdateLDB() end
				}
			}
		},
		icons = {
			name = L["Use icons in LDB feed"],
			desc = nil,
			type = "toggle",
			get = function(info) return Broker_CTA.db.profile.icons end,
			set = function(info, val) Broker_CTA.db.profile.icons = val; Broker_CTA:UpdateLDB() end
		},
		showAllInTooltip = {
			name = L["Show all dungeons in tooltip"],
			desc = nil,
			type = "toggle",
			get = function(info) return Broker_CTA.db.profile.showAllInTooltip end,
			set = function(info, val) Broker_CTA.db.profile.showAllInTooltip = val end
		}
	}
}

for _,id in pairs(CTA_RANDOM_DUNGEONS) do
	defaults.profile.hide.dungeons[tostring(id)] = false
	optionsTable.args.hideDungeons.args[tostring(id)] = {
		name = GetLFGDungeonInfo(id),
		desc = nil,
		type = "toggle",
		get = function(info) return Broker_CTA.db.profile.hide.dungeons[tostring(id)] end,
		set = function(info, val) Broker_CTA.db.profile.hide.dungeons[tostring(id)] = val; Broker_CTA:UpdateLDB() end
	}
	defaults.profile.hide.dungeons['*'] = true
end

function Broker_CTA:MakeIconString(tank, healer, damage, forceIcons)
	local str = ""
	if self.db.profile.icons or forceIcons then
		if tank and not self.db.profile.hide.roles.tank then str = TANK_ICON end
		if healer and not self.db.profile.hide.roles.healer then str = str .. HEALER_ICON end
		if damage and not self.db.profile.hide.roles.damage then str = str .. DPS_ICON end
	else
		if tank and not self.db.profile.hide.roles.tank then str = L["T"] end
		if healer and not self.db.profile.hide.roles.healer then
			if str == "" then str = L["H"] else str = str .. " " .. L["H"] end
		end
		if damage and not self.db.profile.hide.roles.damage then
			if str == "" then str = L["D"] else str = str .. " " .. L["D"] end
		end
	end
	return str
end

function Broker_CTA:Initialize()
	self:UnregisterEvent("PLAYER_LOGIN")
	self.db = LibStub("AceDB-3.0"):New("Broker_CTA_DB", defaults)
	self:RegisterEvent("LFG_UPDATE_RANDOM_INFO", "UpdateLDB")
	self:RequestInfo()
	self:ScheduleRepeatingTimer("RequestInfo", 3)
	LibStub("AceConfig-3.0"):RegisterOptionsTable("Broker_CTA", optionsTable)
	LibStub("AceConfigDialog-3.0"):AddToBlizOptions("Broker_CTA", "Broker CallToArms")
	LibStub("AceConfig-3.0"):RegisterOptionsTable("Broker_CTA_profiles", LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db))
	LibStub("AceConfigDialog-3.0"):AddToBlizOptions("Broker_CTA_profiles", L["Profiles"], "Broker CallToArms")
end

Broker_CTA:RegisterEvent("PLAYER_LOGIN", "Initialize")