LCG = LibStub("LibCustomGlow-1.0")
---@table <string, boolean>
aura_env.BusyFrames = {}

aura_env.Units = {
	"player",
	"party1",
	"party2",
	"party3",
	"party4",
	"party5",
}

---@param unit string
---@return boolean, nil|string
aura_env.HasDispellableDebuff = function(unit)
	for i = 1, 20 do
		local debuff, _, _, _, type = UnitDebuff(unit, i)
		if debuff == nil then return false, nil end
		if type == "Magic" then return true, nil end
	end

	return false, nil
end

---@param frame Frame
---@return string, nil|string
aura_env.GetNameFromFrame = function(frame)
	if frame == nil then return "", "Frame is nil" end
	---@diagnostic disable-next-line: undefined-field
	if frame.Name == nil then return "", "Frame.Name is nil" end
	---@diagnostic disable-next-line: undefined-field
	local name = frame.Name:GetText()
	if name == nil then return "", "Frame.Name.GetText is nil" end
	return name, nil
end

---@param name string
---@return Frame|nil
aura_env.GetFrameFromName = function(name) return aura_env.PartyCache[name] end

---@param name string
---@return string
---@return number
aura_env.RemoveNamePadding = function(name) return string.gsub(name, "|c%w%w%w%w%w%w%w%w", "", 1) end

aura_env.MakeFrameGlow = function(frame)
	local frameName = frame:GetName()
	if frame ~= nil and aura_env.BusyFrames[frameName] == nil then
		---@type Frame
		---@diagnostic disable-next-line: undefined-field
		local healthBar = frame.Health
		if healthBar ~= nil then
			LCG.PixelGlow_Start(healthBar, { 1, 1, 0, 1 }, 16, 0.35, 8, 4)
			aura_env.BusyFrames[frameName] = true
			local aura_env = aura_env
			C_Timer.After(1, function()
				LCG.PixelGlow_Stop(healthBar)
				aura_env.BusyFrames[frameName] = nil
			end)
		end
	end
end

aura_env.PartyCache = {}
aura_env.SetupPartyCache = function()
	for i = 1, 5 do
		-- /dump _G[string.format("ElvUF_RaidGroup1UnitButton%d", 1)].Name:GetText()
		local raidFrame = _G[string.format("ElvUF_RaidGroup1UnitButton%d", i + 1)]
		local name, err = aura_env.GetNameFromFrame(raidFrame)
		if err == nil then
			name = aura_env.RemoveNamePadding(name)
			aura_env.PartyCache[name] = raidFrame
		end
	end
end
