Quantcast
local A, L = ...

-- credit: ndui
local pairs, unpack = pairs, unpack
local buttonConfig = L.C.button
local thinBackdrop = L.C.thin

local function IconBgOnUpdate(self)
	self:SetAlpha(self.__icon:GetAlpha())
	if self.__shadow then
		self.__shadow:SetAlpha(self.__icon:GetAlpha())
	end
end

local function UpdateIconTexCoord(icon)
	if icon.isCutting then return end
	icon.isCutting = true

	local width, height = icon:GetSize()
	if width ~= 0 and height ~= 0 then
		local left, right, top, bottom = unpack(buttonConfig.icon.texCoord) -- normal icon
		local ratio = width/height
		if ratio > 1 then -- fat icon
			local offset = (1 - 1/ratio) / 2
			top = top + offset
			bottom = bottom - offset
		elseif ratio < 1 then -- thin icon
			local offset = (1 - ratio) / 2
			left = left + offset
			bottom = bottom - offset
		end
		icon:SetTexCoord(left, right, top, bottom)
	end

	icon.isCutting = nil
end

local function SkinWeakAuras(f, fType)
	if fType == "icon" then
		if not f.styled then
			UpdateIconTexCoord(f.icon)
			hooksecurefunc(f.icon, "SetTexCoord", UpdateIconTexCoord)
			f.bg = L.CreateBackdrop(f, nil, buttonConfig.backdrop)
			f.bg:SetFrameLevel(0)
			f.bg.__icon = f.icon
			f.bg:HookScript("OnUpdate", IconBgOnUpdate)

			f.styled = true
		end
	elseif fType == "aurabar" then
		if not f.styled then
			f.bg = L.CreateBackdrop(f.bar, nil, thinBackdrop)
			f.bg:SetFrameLevel(0)
			UpdateIconTexCoord(f.icon)
			hooksecurefunc(f.icon, "SetTexCoord", UpdateIconTexCoord)
			f.iconFrame:SetAllPoints(f.icon) -- needs review

			f.styled = true
		end
	end
end

local function ReskinWA()
    if not IsAddOnLoaded("WeakAuras") then return end

	local regionTypes = WeakAuras.regionTypes
	local CreateIcon, ModifyIcon = regionTypes.icon.create, regionTypes.icon.modify
	local CreateAuraBar, ModifyAuraBar = regionTypes.aurabar.create, regionTypes.aurabar.modify

	regionTypes.icon.create = function(parent, data)
		local region = CreateIcon(parent, data)
		SkinWeakAuras(region, "icon")
		return region
	end

	regionTypes.aurabar.create = function(parent)
		local region = CreateAuraBar(parent)
		SkinWeakAuras(region, "aurabar")
		return region
	end

	regionTypes.icon.modify = function(parent, region, data)
		ModifyIcon(parent, region, data)
		SkinWeakAuras(region, "icon")
	end

	regionTypes.aurabar.modify = function(parent, region, data)
		ModifyAuraBar(parent, region, data)
		SkinWeakAuras(region, "aurabar")
	end

	for _, regions in pairs(WeakAuras.regions) do
		if regions.regionType == "icon" or regions.regionType == "aurabar" then
			SkinWeakAuras(regions.region, regions.regionType)
		end
	end
end

rSkin:RegisterSkin("WeakAuras", ReskinWA)