local _, ns = ...
local B, C, L, DB = unpack(ns)
local M = B:GetModule("Misc")

local MapList = {
    --Midnight
    [239] = {1254551}, [556] = {1254555}, [161] = {1254557},[557] = {1254400}, 
	[558] = {1254572},[560] = {1254559}, [559] = {1254563},
    -- Cataclysm
    [438] = {410080}, [456] = {424142}, [507] = {445424},
    -- Pandaria
    [2]={131204},[56]={131205},[57]={131225},[58]={131206},[59]={131228},
    [60]={131222},[76]={131232},[77]={131231},[78]={131229},
    -- Draenor
    [161]={159898},[163]={159895},[164]={159897},[165]={159899},
    [166]={159900},[167]={159902},[168]={159901},[169]={159896},
    -- Legion
    [198]={424163},[199]={424153},[200]={393764},[206]={410078},
    [210]={393766},[227]={373262},[234]={373262},
    -- BfA
    [244]={424187},[245]={410071},[247]={467553,467555},
    [248]={424167},[251]={410074},[353]={445418,464256},[369]={373274},[370]={373274},
    -- Shadowlands
    [375]={354464},[376]={354462},[377]={354468},[378]={354465},
    [379]={354463},[380]={354469},[381]={354466},[382]={354467},
    [391]={367416},[392]={367416},
    -- Dragonflight
    [399]={393256},[400]={393262},[401]={393279},[402]={393273},
    [403]={393222},[404]={393276},[405]={393267},[406]={393283},
    [463]={424197},[464]={424197},
    -- The War Within
    [499]={445444},[500]={445443},[501]={445269},[502]={445416},
    [503]={445417},[504]={445441},[505]={445414},[506]={445440},
    [525]={1216786},[542]={1237215},
}

local SpellList = {}
function M:MDEnhance_UpdateList()
	for mapID, spellIDs in pairs(MapList) do
		local spellID = self:MDEnhance_SelectID(spellIDs)
		if spellID then SpellList[spellID] = mapID end
	end
end

do
	-- 频道选择
	function B.GetMSGChannel()
		return ((IsPartyLFG() or C_PartyInfo.IsPartyWalkIn()) and "INSTANCE_CHAT") or (IsInRaid() and "RAID") or "PARTY"
	end
end

function M:MDEnhance_SelectID(spellIDs)
	if not spellIDs then return end

	if #spellIDs > 1 then
		for _, spellID in pairs(spellIDs) do
			if C_SpellBook.IsSpellKnown(spellID) then
				return spellID
			end
		end
	end

	return spellIDs[1]
end

local function Button_OnEnter(parent, spellID)
	local dungeonIcon = parent:GetParent()
	if not dungeonIcon then return end

	local dungeonIcon_OnEnter = dungeonIcon:GetScript("OnEnter")
	if dungeonIcon_OnEnter then dungeonIcon_OnEnter(dungeonIcon) end

	local _, _, timeLimit = C_ChallengeMode.GetMapUIInfo(dungeonIcon.mapID)
	GameTooltip:AddLine(L["+2timeLimit"]..SecondsToClock(timeLimit*.8), 1, 1, 0)
	GameTooltip:AddLine(L["+3timeLimit"]..SecondsToClock(timeLimit*.6), 0, 1, 0)
	--GameTooltip:AddLine(" ")

	if spellID then
		local name = C_Spell.GetSpellName(spellID)
		local CDInfo = C_Spell.GetSpellCooldown(spellID)

		if C_SpellBook.IsSpellKnown(spellID) and CDInfo then
			if CDInfo.duration == 0 then
				GameTooltip:AddLine(name, 0,1,0)
			else
				GameTooltip:AddLine(name, 1,1,0)
			end
		else
			GameTooltip:AddLine(name, 1,0,0)
		end
	else
		GameTooltip:AddLine(SPELL_FAILED_NOT_KNOWN, 1,0,0)
	end

	--GameTooltip:AddLine(" ")
	if IsShiftKeyDown() then GameTooltip:AddLine(L["MapID"]..dungeonIcon.mapID, 1, 1, 1) end

	GameTooltip:Show()
end

local function Button_OnLeave(parent)
	GameTooltip:Hide()
end

function M:MDEnhance_UpdateEnhance(parent, spellIDs)
	if not parent then return end
	parent.BScore:SetText("")

	local spellID = self:MDEnhance_SelectID(spellIDs)
	parent.TButton:SetAttribute("type", "spell")
	parent.TButton:SetAttribute("spell", spellID)
	parent.TButton:SetScript("OnEnter", function(parent) Button_OnEnter(parent, spellID) end)
	parent.TButton:SetScript("OnLeave", function(parent) Button_OnLeave(parent) end)

	local affixScores, bestScore = C_MythicPlus.GetSeasonBestAffixScoreInfoForMap(parent.mapID)
	if not affixScores or not bestScore then return end

	local color = C_ChallengeMode.GetSpecificDungeonOverallScoreRarityColor(bestScore) or HIGHLIGHT_FONT_COLOR
	parent.BScore:SetText(bestScore and bestScore or "")
	parent.BScore:SetTextColor(color.r, color.g, color.b)

--[[
	parent.FScore:SetText(affixScores[1] and affixScores[1].score or "")
	parent.FScore:SetTextColor(1, 1, 0)

	parent.TScore:SetText(affixScores[2] and affixScores[2].score or "")
	parent.TScore:SetTextColor(0, 1, 1)
]]
end

function M:MDEnhance_CreateEnhance(parent)
	if not parent then return end

	local TButton = CreateFrame("Button", nil, parent, "InsecureActionButtonTemplate")
	TButton:SetAllPoints(parent)
	TButton:RegisterForClicks("AnyDown")

	parent.TButton = TButton
	parent.BScore = B.CreateFS(parent, 18, "", false, "BOTTOM", 0, 0)
	parent.FScore = B.CreateFS(parent, 16, "", false, "BOTTOMLEFT", 0, 0)
	parent.TScore = B.CreateFS(parent, 16, "", false, "BOTTOMRIGHT", 0, 0)
end

function M.MDEnhance_OnUpdate()
	if InCombatLockdown() or not ChallengesFrame or not ChallengesFrame.DungeonIcons then return end

	for _, dungeonIcon in pairs(ChallengesFrame.DungeonIcons) do
		if not dungeonIcon.TButton then
			M:MDEnhance_CreateEnhance(dungeonIcon)
		end
		M:MDEnhance_UpdateEnhance(dungeonIcon, MapList[dungeonIcon.mapID])
	end
end

function M.MDEnhance_OnCreate()
	hooksecurefunc(ChallengesFrame, "Update", M.MDEnhance_OnUpdate)
end

function M:MDEnhance_Notification(unit, casterID, spellID)
	if unit == "player" and SpellList[spellID] then
		B:SendChatMessage(format(L["CastAlertInfo"], C_Spell.GetSpellLink(spellID) or C_Spell.GetSpellName(spellID), C_ChallengeMode.GetMapUIInfo(SpellList[spellID])), B.GetMSGChannel())
	end
end

function M:MDEnhance_CheckGroup()
	if IsInGroup() and not IsInInstance() then
		B:RegisterEvent("UNIT_SPELLCAST_START", M.MDEnhance_Notification)
	else
		B:UnregisterEvent("UNIT_SPELLCAST_START", M.MDEnhance_Notification)
	end
end

	function B:LoadAddOns(name, func)
		local function loadFunc(event, addon)
			if event == "PLAYER_ENTERING_WORLD" then
				B:UnregisterEvent(event, loadFunc)

				local isLoaded, isFinished = C_AddOns.IsAddOnLoaded(name)
				if isLoaded and isFinished then
					xpcall(func, geterrorhandler())
					B:UnregisterEvent("ADDON_LOADED", loadFunc)
				end
			elseif event == "ADDON_LOADED" and addon == name then
				xpcall(func, geterrorhandler())
				B:UnregisterEvent(event, loadFunc)
			end
		end

		B:RegisterEvent("PLAYER_ENTERING_WORLD", loadFunc)
		B:RegisterEvent("ADDON_LOADED", loadFunc)
	end
	
function M:MDEnhance()
	M:MDEnhance_UpdateList()
	M:MDEnhance_CheckGroup()

	B:LoadAddOns("Blizzard_ChallengesUI", M.MDEnhance_OnCreate)
	B:RegisterEvent("GROUP_ROSTER_UPDATE", M.MDEnhance_CheckGroup)
end
