local _G = _G
local IRF3 = _G[...]
local pairs = _G.pairs
local wipe = _G.table.wipe
local InCombatLockdown = _G.InCombatLockdown
local GetActiveTalentGroup = _G.GetActiveTalentGroup
local talent, ctype, ckey1, ckey2
local modifilters = { [""] = true, ["alt-"] = true, ["ctrl-"] = true, ["shift-"] = true, ["alt-ctrl-"] = true, ["alt-shift-"] = true, ["ctrl-shift-"] = true }

IRF3.numMouseButtons = 15

local function reset(member, modifilter, button, ctype)
	member:SetAttribute(modifilter.."type"..button, ctype)
	member:SetAttribute(modifilter.."spell"..button, nil)
	member:SetAttribute(modifilter.."item"..button, nil)
	member:SetAttribute(modifilter.."macro"..button, nil)
	member:SetAttribute(modifilter.."macrotext"..button, nil)
end

function IRF3:GetClickCasting(modifilter, button)
	talent = IRF3.ccdb[modifilter..button]
	if talent then
		ctype, ckey1 = talent:match("(.+)__(.+)")
		if ctype == "macrotext" then
			return "macro", ctype, ckey1
		elseif ctype then
			return ctype, ctype, ckey1
		else
			return talent
		end
	end
	return nil
end

function IRF3:SetClickCasting(modifilter, button)
	ctype, ckey1, ckey2 = self:GetClickCasting(modifilter, button)
	if ckey1 then
		for _, header in pairs(IRF3.headers) do
			for _, member in pairs(header.members) do
				reset(member, modifilter, button, ctype)
				member:SetAttribute(modifilter..ckey1..button, ckey2)
				reset(member.petButton, modifilter, button, ctype)
				member.petButton:SetAttribute(modifilter..ckey1..button, ckey2)
			end
		end
		for _, member in pairs(IRF3.petHeader.members) do
			reset(member, modifilter, button, ctype)
			member:SetAttribute(modifilter..ckey1..button, ckey2)
		end
	else
		for _, header in pairs(IRF3.headers) do
			for _, member in pairs(header.members) do
				reset(member, modifilter, button, ctype)
				reset(member.petButton, modifilter, button, ctype)
			end
		end
		for _, member in pairs(IRF3.petHeader.members) do
			reset(member, modifilter, button, ctype)
		end
	end
end

function IRF3:SelectClickCastingDB()
	if InCombatLockdown() or not InvenRaidFrames3CharDB then return end
	InvenRaidFrames3CharDB.clickCasting = InvenRaidFrames3CharDB.clickCasting or { {}, {} }
	IRF3.talent, talent = GetActiveTalentGroup() or 1, IRF3.talent
	if IRF3.talent ~= talent then
		IRF3.ccdb = InvenRaidFrames3CharDB.clickCasting[IRF3.talent]
		for modifilter in pairs(modifilters) do
			for button = 1, IRF3.numMouseButtons do
				IRF3:SetClickCasting(modifilter, button)
			end
		end
		if IRF3.optionFrame.UpdateClickCasting then
			IRF3.optionFrame:UpdateClickCasting()
		end
	end
end

local handler = CreateFrame("Frame")
handler:SetScript("OnEvent", IRF3.SelectClickCastingDB)
handler:RegisterEvent("PLAYER_TALENT_UPDATE")
handler:RegisterEvent("PLAYER_ENTERING_WORLD")
handler:RegisterEvent("PLAYER_REGEN_ENABLED")