local init_done
local conf
XPerl_RequestConfig(function(new) conf = new end)

-- SetTex
local highlightPositions = {{0, 0.25, 0, 0.5}, {0.25, 0.75, 0, 0.5}, {0, 1, 0.5, 1}, {0.75, 1, 0, 0.5}}
local function SetTex(self, num)
	local p = highlightPositions[num]

	if (self:GetFrameType() == "Button") then
		if (conf.HighlightSelection == 1) then
			self:SetHighlightTexture("Interface\\Addons\\XPerl\\images\\XPerl_Highlight", "ADD")
			local tex = self:GetHighlightTexture()
			tex:SetTexCoord(p[1], p[2], p[3], p[4])
			tex:SetVertexColor(0.86, 0.82, 0.41)
		else
			self:SetHighlightTexture("")
		end

	elseif (self:GetFrameType() == "Frame") then
		if (self.tex) then
			self.tex:SetTexture("Interface\\Addons\\XPerl\\images\\XPerl_Highlight", "ADD")
			self.tex:SetTexCoord(p[1], p[2], p[3], p[4])
			self.tex:SetVertexColor(0.86, 0.82, 0.41)
			XPerl_Highlight:SetHighlight(self:GetParent())
		end
	end
end

-- RegisterHighlight
local HighlightFrames = {}
function XPerl_RegisterHighlight(frame, ratio)
	HighlightFrames[frame] = ratio
	if (init_done) then
		SetTex(frame, ratio)
	end
end

-- XPerl_SetHighlights
function XPerl_SetHighlights()
	for k,v in pairs(HighlightFrames) do
		SetTex(k, v)
	end
end

-- SetupUnitFrame
local function SetupUnitFrame(argFrame)
	argFrame:SetBackdropBorderColor(conf.BorderColour.r, conf.BorderColour.g, conf.BorderColour.b, conf.BorderColour.a)
	argFrame:SetBackdropColor(conf.BackColour.r, conf.BackColour.g, conf.BackColour.b, conf.BackColour.a)
end

-- SetupUnitFrameList
local function SetupUnitFrameList(frame, subList)
	if (type(subList) == "table") then
		frame:SetAlpha(conf.Transparency)
		for k,v in pairs(subList) do
			SetupUnitFrame(v)
		end
	else
		SetupUnitFrame(frame)
	end
end

-- XPerl_RegisterUnitFrame(frame)
local UnitFrames = {}
function XPerl_RegisterPerlFrames(frame, subList)
	if (not subList) then
		subList = true
	end
	UnitFrames[frame] = subList

	if (init_done) then
		SetupUnitFrameList(frame, subList)
	end
end

-- XPerl_SetupAllPerlFrames
function XPerl_SetupAllPerlFrames(frame)
	for k,v in pairs(UnitFrames) do
		SetupUnitFrameList(k, v)
	end
end

-- XPerl_SetAllFrames
function XPerl_SetAllFrames()
	XPerl_SetupAllPerlFrames()
	XPerl_SetHighlights()

	for k,v in pairs({XPerl_Player, XPerl_Target, XPerl_Focus, XPerl_TargetTarget, XPerl_TargetTargetTarget}) do
		if (v) then
			v.nameFrame.pvpRankIcon:SetAlpha(0.3)
		end
	end
end

-- Buff Tooltip Hook
local function XPerl_GameTooltipSetPlayerBuff(self, id)
	if (this.buffFilter == "HELPFUL" or (ElkBuffButton1 and this.type == "BUFF")) then
		XPerl_ToolTip_AddBuffDuration("player", self)
	end
end

-- XPerl_Init()
function XPerl_Init()
	init_done = true
	hooksecurefunc(GameTooltip, "SetPlayerBuff", XPerl_GameTooltipSetPlayerBuff)

	-- Check for eCastbar and disable old frame if used.
	if (eCastingBar_Saved and eCastingBar_Player and eCastingBar_Saved[eCastingBar_Player].Enabled == 1) then
		conf.OldCastBar = 0
	elseif (BCastBar and BCastingBar and BCastBarDragButton) then
		conf.OldCastBar = 0
	end

	XPerl_OptionActions()

	local name, title, notes, enabled = GetAddOnInfo("PerlButton")
	if (name and enabled) then
		DisableAddOn("PerlButton")
		XPerl_Notice("Disabled 'PerlButton' addon. It is not compatible or needed with X-Perl")
		-- PerlButton was made for Nymbia's Perl UnitFrames. We have our own minimap button
	end

	name, title, notes, enabled = GetAddOnInfo("WT_ZoningTimeFix")
	if (name and enabled) then
		DisableAddOn("WT_ZoningTimeFix")
		XPerl_Notice("Disabled 'WT_ZoningTimeFix' addon. It is not compatible with X-Perl, and creates display issues.")
	end

	name, title, notes, enabled = GetAddOnInfo("CT_PartyBuffs")
	if (name and enabled) then
		DisableAddOn("CT_PartyBuffs")
		XPerl_Notice("Disabled 'CT_PartyBuffs' addon. It is not compatible with X-Perl, and creates display issues.")
	end
	if (CT_PartyBuffFrame1) then
		CT_PartyBuffFrame1:Hide()
		CT_PartyBuffFrame2:Hide()
		CT_PartyBuffFrame3:Hide()
		CT_PartyBuffFrame4:Hide()
		CT_PetBuffFrame:Hide()
	end

	name, title, notes, enabled = GetAddOnInfo("SupportFuncs")
	if (name and enabled) then
		local ver = GetAddOnMetadata(name, "Version")
		if (tonumber(ver) < 20000.2) then
			XPerl_Notice("Out-dated version of SupportFuncs addon detected. This will break the X-Perl Range Finder by replacing standard Blizzard API functions.")
		end
	end

	if (EarthFeature_AddButton) then
		EarthFeature_AddButton ({name = XPerl_ProductName,
					icon = XPerl_ModMenuIcon,
					subtext = "by "..XPerl_Author,
					tooltip = XPerl_LongDescription,
					callback = XPerl_Toggle})
	end

	if(CT_RegisterMod) then
		CT_RegisterMod(XPerl_ProductName.." "..XPerl_VersionNumber, "By "..XPerl_Author, 4, XPerl_ModMenuIcon, XPerl_LongDescription, "switch", "", XPerl_Toggle)
	end

	if (myAddOnsFrame) then
                myAddOnsList.XPerl_Description = {
                        name			= XPerl_Description,
                        description		= XPerl_LongDescription,
                        version			= XPerl_VersionNumber,
                        category		= MYADDONS_CATEGORY_OTHERS,
                        frame			= "XPerl_Globals",
                        optionsframe		= "XPerl_Options"
                        }
	end

	--if (not strfind("Zek Hek Zeks Zekked Zekstuff Pooksie Wazek", UnitName("player")) or GetRealmName() ~= "Bloodhoof") then
	--	XPerl_ShowMessage = function() end
	--end

	XPerl_Init = nil
end

-- XPerl_StatsFrame_Setup
function XPerl_StatsFrameSetup(self, others, offset)
	if (not self) then
		return
	end
	local StatsFrame = self.statsFrame
	if (not StatsFrame) then
		return
	end

        local healthBar = StatsFrame.healthBar
        local healthBarText = healthBar.text
        local healthBarPercent = healthBar.percent
        local manaBar = StatsFrame.manaBar
        local manaBarPercent = manaBar.percent
	local otherBars = {}
	local secondaryBarsShown = 0
	local showPercent = 0
	if (healthBarPercent:IsShown() or manaBarPercent:IsShown()) then
		showPercent = 1
	end
        local percentSize = showPercent * 35;   -- 0 means 0, 1 means 32 offset (+3 for spacing after text), which is our size difference

	offset = (offset or 0)

	if (manaBar:IsShown()) then
		secondaryBarsShown = secondaryBarsShown + 1
	end

	local needTicker = 0
	if (conf.EnergyTicker == 1 and StatsFrame == XPerl_PlayerstatsFrame and UnitPowerType("player") == 3) then
		needTicker = 1
	end

	if (others) then
		for i,other in pairs(others) do
			local bar = getglobal(StatsFrame:GetName()..other)
			if (bar) then
				tinsert(otherBars, bar)

				if (bar:IsShown()) then
					secondaryBarsShown = secondaryBarsShown + 1
				end
			else
				if (not bar) then XPerl_Notice("No frame found called '"..StatsFrame:GetName()..other.."'"); end
			end
		end
	end

	if (conf.FatHealthBars == 1) then
		if (StatsFrame == XPerl_Player_PetstatsFrame) then
			healthBarText:SetFontObject(GameFontNormalSmall)
		else
			healthBarText:SetFontObject(GameFontNormal)
		end

        	healthBar:ClearAllPoints()
        	healthBar:SetPoint("TOPLEFT", 5, -5)
        	healthBar:SetPoint("BOTTOMRIGHT", -(5 + percentSize), 5 + needTicker + (secondaryBarsShown * 10))

        	manaBar:ClearAllPoints()
        	manaBar:SetPoint("BOTTOMLEFT", 5, -5 + needTicker + (secondaryBarsShown * 10))
        	manaBar:SetPoint("TOPRIGHT", healthBar, "BOTTOMRIGHT", 0, 0)

		local lastBar = manaBar
		local tickerSpace = needTicker * 2
		for i,bar in pairs(otherBars) do
			if (bar:IsShown()) then
        	        	bar:ClearAllPoints()

        	        	bar:SetPoint("TOPLEFT", lastBar, "BOTTOMLEFT", 0, -tickerSpace)
        	        	bar:SetPoint("BOTTOMRIGHT", lastBar, "BOTTOMRIGHT", 0, -10 - tickerSpace)

				lastBar = bar
				tickerSpace = 0
			end
        	end
	else
		healthBarText:SetFontObject(GameFontNormalSmall)

        	healthBar:ClearAllPoints()
        	healthBar:SetPoint("TOPLEFT", 8, -9 + offset)
        	healthBar:SetPoint("BOTTOMRIGHT", StatsFrame, "TOPRIGHT", -(8 + percentSize), -19 + offset)

        	manaBar:ClearAllPoints()
        	manaBar:SetPoint("TOPLEFT", healthBar, "BOTTOMLEFT", 0, -2)
        	manaBar:SetPoint("BOTTOMRIGHT", healthBar, "BOTTOMRIGHT", 0, -12)

		local lastBar = manaBar
		for i,bar in pairs(otherBars) do
			if (bar:IsShown()) then
        	        	bar:ClearAllPoints()

        	        	bar:SetPoint("TOPLEFT", lastBar, "BOTTOMLEFT", 0, -2)
        	        	bar:SetPoint("BOTTOMRIGHT", lastBar, "BOTTOMRIGHT", 0, -12)

				lastBar = bar
			end
        	end
	end
end

-- XPerl_SetTextTransparencyFrame
function XPerl_SetTextTransparencyFrame(self)
	local subFrames = {"healthBartext", "healthBarpercent", "manaBartext", "manaBarpercent"}

	for k,v in pairs(subFrames) do
		local f = getglobal(self:GetName().."statsFrame"..v)
		if (f) then
			f:SetTextColor(1,1,1,conf.TextTransparency)
		else
			XPerl_Notice("No text frame found called '"..self:GetName().."statsFrame"..v.."'")
		end
	end
end

-- XPerl_SetTextTransparency
local function XPerl_SetTextTransparency(num)

	local statFrames = {XPerl_Player, XPerl_Player_Pet, XPerl_Target, XPerl_Focus, XPerl_TargetTarget, XPerl_TargetTargetTarget,
				XPerl_party1, XPerl_party2, XPerl_party3, XPerl_party4,
				XPerl_partypet1, XPerl_partypet2, XPerl_partypet3, XPerl_partypet4}

	for k,v in pairs(statFrames) do
		XPerl_SetTextTransparencyFrame(v)
	end

	if (XPerl_Player) then
		XPerl_Player.statsFrame.druidBar.text:SetTextColor(1,1,1,conf.TextTransparency)
		XPerl_Player.statsFrame.druidBar.percent:SetTextColor(1,1,1,conf.TextTransparency)
		XPerl_Player.statsFrame.xpBar.text:SetTextColor(1,1,1,conf.TextTransparency)
		XPerl_Player.statsFrame.xpBar.percent:SetTextColor(1,1,1,conf.TextTransparency)
		XPerl_Player.statsFrame.repBar.text:SetTextColor(1,1,1,conf.TextTransparency)
		XPerl_Player.statsFrame.repBar.percent:SetTextColor(1,1,1,conf.TextTransparency)
	end
end

-- XPerl_GetBarTexture
function XPerl_GetBarTexture()
	if (conf.BarTextures == 0) then
		return "Interface\\TargetingFrame\\UI-StatusBar"
	elseif (conf.BarTextures == 1) then
		return "Interface\\AddOns\\XPerl\\Images\\XPerl_StatusBar"
	else
		return "Interface\\AddOns\\XPerl\\Images\\XPerl_StatusBar"..conf.BarTextures
	end
end

-- Set1Bar
local function Set1Bar(bar, tex)
	if (bar.tex) then
		bar.tex:SetTexture(tex)
	end
	if (bar.bg) then
		if (conf.BackgroundTextures == 1) then
			bar.bg:SetTexture(tex)
		else
			bar.bg:SetTexture("Interface\\TargetingFrame\\UI-StatusBar")
		end
	end
end

-- XPerl_RegisterBar
local XPerlBars = {}
function XPerl_RegisterBar(bar)
	tinsert(XPerlBars, bar)
	if (init_done) then
		local tex = XPerl_GetBarTexture()
		Set1Bar(bar, tex)
	end
end

-- XPerl_SetBarTextures
function XPerl_SetBarTextures()
	local tex = XPerl_GetBarTexture()
	for k,v in pairs(XPerlBars) do
		Set1Bar(v, tex)
	end

	if (XPerl_Player) then
		XPerl_Player.statsFrame.druidBar:SetStatusBarColor(conf.ColourMana.r, conf.ColourMana.g, conf.ColourMana.b)
		XPerl_Player.statsFrame.druidBar.bg:SetVertexColor(conf.ColourMana.r, conf.ColourMana.g, conf.ColourMana.b, 0.25)
	end
end

-- XPerl_RegisterOptionChanger
local optionFuncs = {}
function XPerl_RegisterOptionChanger(f, s)
	tinsert(optionFuncs, {func = f, slf = s})
end

-- XPerl_OptionActions()
function XPerl_OptionActions(which)

	if (InCombatLockdown()) then
		XPerl_OutOfCombatOptionSet = true
		return
	end

	if (conf.ShowTutorials) then
		if (not IsAddOnLoaded("XPerl_Tutorial")) then
			EnableAddOn("XPerl_Tutorial")
			LoadAddOn("XPerl_Tutorial")
		end
	end

	conf.Transparency	= min(max(tonumber(conf.Transparency or 1), 0), 1)
	conf.TextTransparency	= min(max(tonumber(conf.TextTransparency or 1), 0), 1)

	for k,v in pairs({"PlayerFrame", "PetFrame", "PartyFrame", "PartyPets", "TargetFrame", "FocusFrame", "TargetTargetFrame", "Raid"}) do
		conf["Scale_"..v] = min(max(tonumber(conf["Scale_"..v]), 0.5), conf.MaximumScale)
	end

	XPerl_SetBarTextures()

	for k,v in pairs(optionFuncs) do
		XPerl_NoFadeBars(true)
		v.func(v.slf, which)
	end
	XPerl_NoFadeBars()

	XPerl_SetAllFrames()
	XPerl_SetTextTransparency(conf.TextTransparency)
end
