local _, ns = ...
local oUF = ns.oUF
local Private = oUF.Private

local frame_metatable = Private.frame_metatable
local nierror = Private.nierror

local colorMixin = {
	SetAtlas = function(self, atlas)
		local info = C_Texture.GetAtlasInfo(atlas)
		if not info then
			return nierror(string.format('"%s" is an invalid atlas.', atlas))
		end

		self.atlas = atlas
	end,
	GetAtlas = function(self)
		return self.atlas
	end,
	SetCurve = function(self, ...)
		if ... then
			if self.curve then
				self.curve:ClearPoints()
			else
				self.curve = C_CurveUtil.CreateColorCurve()
			end

			if type(...) == 'table' then
				for x, y in next, (...) do
					self.curve:AddPoint(x, y)
				end
			else
				for i = 1, select('#', ...), 2 do
					self.curve:AddPoint(select(i, ...), select(i + 1, ...))
				end
			end
		else
			self.curve = nil
		end
	end,
	GetCurve = function(self)
		return self.curve
	end,
}

--[[ Colors: oUF:CreateColor(r, g, b[, a])
Wrapper for [Blizzard_SharedXMLBase/Color.lua's ColorMixin](https://warcraft.wiki.gg/wiki/ColorMixin), extended with extra methods for dealing with
atlases and curves.

The rgb values can be either normalized (0-1) or bytes (0-255).

* self - the global oUF object
* r    - value used as represent the red color (number)
* g    - value used to represent the green color (number)
* b    - value used to represent the blue color (number)
* a    - value used to represent the opacity (number, optional)

## Returns

* color - the ColorMixin-based object
--]]
function oUF:CreateColor(r, g, b, a)
	if r > 1 or g > 1 or b > 1 then
		r, g, b = r / 255, g / 255, b / 255
	end

	local color = Mixin({}, ColorMixin, colorMixin)
	color:SetRGBA(r, g, b, a)

	-- provide a default curve for smooth colors
	color:SetCurve({
		[0] = CreateColor(1, 0, 0),
		[0.5] = CreateColor(1, 1, 0),
		[1] = CreateColor(0, 1, 0),
	})

	return color
end

local colors = {
	health = oUF:CreateColor(49, 207, 37),
	disconnected = oUF:CreateColor(0.6, 0.6, 0.6),
	tapped = oUF:CreateColor(0.6, 0.6, 0.6),
	runes = {
		oUF:CreateColor(247, 65, 57), -- blood
		oUF:CreateColor(148, 203, 247), -- frost
		oUF:CreateColor(173, 235, 66), -- unholy
	},
	selection = {
		-- https://warcraft.wiki.gg/wiki/API_UnitSelectionColor
		[oUF.Enum.SelectionType.Hostile] = oUF:CreateColor(255, 0, 0),
		[oUF.Enum.SelectionType.Unfriendly] = oUF:CreateColor(255, 128, 0),
		[oUF.Enum.SelectionType.Neutral] = oUF:CreateColor(255, 255, 0),
		[oUF.Enum.SelectionType.Friendly] = oUF:CreateColor(0, 255, 0),
		[oUF.Enum.SelectionType.PlayerSimple] = oUF:CreateColor(0, 0, 255),
		[oUF.Enum.SelectionType.PlayerExtended] = oUF:CreateColor(96, 96, 255),
		[oUF.Enum.SelectionType.Party] = oUF:CreateColor(170, 170, 255),
		[oUF.Enum.SelectionType.PartyPvP] = oUF:CreateColor(170, 255, 170),
		[oUF.Enum.SelectionType.Friend] = oUF:CreateColor(83, 201, 255),
		[oUF.Enum.SelectionType.Dead] = oUF:CreateColor(128, 128, 128),
		[oUF.Enum.SelectionType.PartyPvPInBattleground] = oUF:CreateColor(0, 153, 0),
		[oUF.Enum.SelectionType.RecentAlly] = oUF:CreateColor(83, 201, 255),
	},
	class = {},
	dispel = {},
	reaction = {},
	power = {},
	threat = {},
}

-- We do this because people edit the vars directly, and changing the default
-- globals makes SPICE FLOW!
local function customClassColors()
	if _G.CUSTOM_CLASS_COLORS then
		local function updateColors()
			for classToken, color in next, _G.CUSTOM_CLASS_COLORS do
				colors.class[classToken] = oUF:CreateColor(color.r, color.g, color.b)
			end

			for _, obj in next, oUF.objects do
				obj:UpdateAllElements('CUSTOM_CLASS_COLORS')
			end
		end

		updateColors()
		_G.CUSTOM_CLASS_COLORS:RegisterCallback(updateColors)

		return true
	end
end

if not customClassColors() then
	for classToken, color in next, _G.RAID_CLASS_COLORS do
		colors.class[classToken] = oUF:CreateColor(color.r, color.g, color.b)
	end

	local eventHandler = CreateFrame('Frame')
	eventHandler:RegisterEvent('ADDON_LOADED')
	eventHandler:RegisterEvent('PLAYER_ENTERING_WORLD')
	eventHandler:SetScript('OnEvent', function(self)
		if customClassColors() then
			self:UnregisterAllEvents()
			self:SetScript('OnEvent', nil)
		end
	end)
end

-- copy of DEBUFF_DISPLAY_INFO from AuraUtil
colors.dispel[oUF.Enum.DispelType.None] = _G.DEBUFF_TYPE_NONE_COLOR
colors.dispel[oUF.Enum.DispelType.Magic] = _G.DEBUFF_TYPE_MAGIC_COLOR
colors.dispel[oUF.Enum.DispelType.Curse] = _G.DEBUFF_TYPE_CURSE_COLOR
colors.dispel[oUF.Enum.DispelType.Disease] = _G.DEBUFF_TYPE_DISEASE_COLOR
colors.dispel[oUF.Enum.DispelType.Poison] = _G.DEBUFF_TYPE_POISON_COLOR
colors.dispel[oUF.Enum.DispelType.Bleed] = _G.DEBUFF_TYPE_BLEED_COLOR
colors.dispel[oUF.Enum.DispelType.Enrage] = oUF:CreateColor(243, 95, 245)

for eclass, color in next, _G.FACTION_BAR_COLORS do
	colors.reaction[eclass] = oUF:CreateColor(color.r, color.g, color.b)
end

local stageIndices = {
	-- stagger
	green = 1,
	yellow = 2,
	red = 3,
	-- soul fragments
	voidMetamorphosisProgess = 1,
	collapsingStarProgess = 2,
}

for power, color in next, PowerBarColor do
	if type(power) == 'string' then
		if color.r then
			colors.power[power] = oUF:CreateColor(color.r, color.g, color.b)

			if color.atlas then
				colors.power[power]:SetAtlas(color.atlas)
			end

			if color.atlasElementName then
				colors.power[power]:SetAtlas('UI-HUD-UnitFrame-Player-PortraitOn-Bar-' .. color.atlasElementName)
			end
		else
			-- special handling of colours with stages
			colors.power[power] = {}

			for name, color_ in next, color do
				local index = stageIndices[name]
				if index then
					colors.power[power][index] = oUF:CreateColor(color_.r, color_.g, color_.b)

					if color_.atlas then
						colors.power[power][index]:SetAtlas(color_.atlas)
					end
				end
			end
		end
	end
end

-- fallback integer index to named index
-- sourced from PowerBarColor - Blizzard_UnitFrame/Mainline/PowerBarColorUtil.lua
colors.power[Enum.PowerType.Mana or 0] = colors.power.MANA
colors.power[Enum.PowerType.Rage or 1] = colors.power.RAGE
colors.power[Enum.PowerType.Focus or 2] = colors.power.FOCUS
colors.power[Enum.PowerType.Energy or 3] = colors.power.ENERGY
colors.power[Enum.PowerType.ComboPoints or 4] = colors.power.COMBO_POINTS
colors.power[Enum.PowerType.Runes or 5] = colors.power.RUNES
colors.power[Enum.PowerType.RunicPower or 6] = colors.power.RUNIC_POWER
colors.power[Enum.PowerType.SoulShards or 7] = colors.power.SOUL_SHARDS
colors.power[Enum.PowerType.LunarPower or 8] = colors.power.LUNAR_POWER
colors.power[Enum.PowerType.HolyPower or 9] = colors.power.HOLY_POWER
colors.power[Enum.PowerType.Maelstrom or 11] = colors.power.MAELSTROM
colors.power[Enum.PowerType.Insanity or 13] = colors.power.INSANITY
colors.power[Enum.PowerType.Fury or 17] = colors.power.FURY
colors.power[Enum.PowerType.Pain or 18] = colors.power.PAIN

-- these two don't have fallback values in PowerBarColor, but we want them
colors.power[Enum.PowerType.Chi or 12] = colors.power.CHI
colors.power[Enum.PowerType.ArcaneCharges or 16] = colors.power.ARCANE_CHARGES

-- there's no official colour for evoker's essence
-- use the average colour of the essence texture instead
colors.power.ESSENCE = oUF:CreateColor(100, 173, 206)
colors.power[Enum.PowerType.Essence or 19] = colors.power.ESSENCE

-- alternate power, sourced from Blizzard_UnitFrame/Mainline/CompactUnitFrame.lua
colors.power.ALTERNATE = oUF:CreateColor(0.7, 0.7, 0.6)
colors.power[Enum.PowerType.Alternate or 10] = colors.power.ALTERNATE

-- fake power types, no ID equivalent will exist to avoid collisions
colors.power.ICICLES = oUF:CreateColor(116, 217, 246) -- based on spell icon
colors.power.TIP_OF_THE_SPEAR = oUF:CreateColor(108, 188, 40) -- based on spell icon

for i = 0, 3 do
	colors.threat[i] = oUF:CreateColor(GetThreatStatusColor(i))
end

oUF.colors = colors

frame_metatable.__index.colors = colors
