--[[========================================================================================
	
	
	Author: Ferodra [Arenima - Alleria EU]
		Email: ferodra@gmx.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
    ========================================================================================]]

--[[===========================
			Globals
=============================]]
local _
local L, CO, Minimap, Worldmap, Chat, Tooltip, Unitframes, Auras, Bar_Auras, Core, Bar_Experience, Bar_Cast, Layout, AB, B

-- TITLE defines the AddOn name!
local TITLE, E							= 			... -- AddOn-Title, Engine init
E.LibSmooth								=			LibStub("LibSmoothStatusBar-1.0")
E 										= 			LibStub("AceAddon-3.0"):NewAddon(E, "CUI", "AceHook-3.0")

local CUI = E
setmetatable(CUI, { __index = _G })
--[[===========================
			CUI Parent
=============================]]
E.Parent								=			CreateFrame("Frame", "EParent", UIParent)
do
	E.Parent:SetSize(UIParent:GetSize())
	E.Parent:SetFrameLevel(UIParent:GetFrameLevel())
	E.Parent:SetPoint("BOTTOM", UIParent, "BOTTOM")
	
	E.ClientVersion, E.ClientBuild = GetBuildInfo()
end
--[[===========================
			Core Begin
=============================]]

E.Debug									=			false
E.Version								=			"0.4.2 Release"
E.VersionDate							=			"July 4th 2018"


E.DifficultyColor						=			"|cffFF4500"  --DIFFICULTY COLOR
E.ColorReset 							= 			"|r"
local bracketColor						=			"|cffFF4500"
local bracketO 							= 			string.format("%s<%s", bracketColor, E.ColorReset)
local bracketC 							= 			string.format("%s>%s", bracketColor, E.ColorReset)
local prefixColor 						= 			"|cffffcc00"
E.MessageColor 						= 			"|cff00ccff"
E.PrintPrefix 						= 			string.format("%s%s%s%s%s", bracketO, prefixColor, TITLE, E.ColorReset, bracketC)

function E:RegisterEvents(obj, ...)
	for i=1,select('#', ...) do
		obj:RegisterEvent(select(i, ...))
	end
end

local alerts = {"StoreMicroButtonAlert","EJMicroButtonAlert","LFDMicroButtonAlert","CollectionsMicroButtonAlert","TalentMicroButtonAlert"}

-- /run E:MainMenuMicroButton_RepositionAlerts()
-- @TODO: Move MicroMenu methods to external file
function E:MainMenuMicroButton_RepositionAlerts()
	for _, alert in pairs(alerts) do
		if _G[alert].MicroButton then
			E:MainMenuMicroButton_PositionAlert(_G[alert])
		end
	end
end

function E:IsLegionClient()
	if E.ClientVersion == "7.3.5" then return true else return false end
end

-- Provide full modularity by simply separating every UI module.
-- This also allows plugins that can be embedded in the users config (custom code etc)
E.Modules = {}
function E:AddModule(name, object)
	-- Store in Engine
	if E.Modules[name] then
		table.insert(E.Modules[name], object)
	else
		E.Modules[name] 			= object
	end
	
	E.Modules[name].initialized = false
	if E.Modules[name].Autoload then
		E:QueueModuleAutoload(name)
	end
	
	return
end

-- Prevent pre-loading the module before anything else (db)
function E:InitializeModule(name)
	return E.Modules[name]:Init()
end

-- Load module reference on demand and initialize if @param2 is true and module wasnt initialized yet
function E:GetModule(name, init)
	if init == true and E.Modules[name] and E.Modules[name].initialized == false then
		E:InitializeModule(name)
		E.Modules[name].initialized = true
	end
	return E.Modules[name]
end

-- Mass-loading modules into other files
function E:LoadModules(...)
	local CurrentModule
	local Modules = {}
	for i=1,select('#', ...) do
		CurrentModule = E:GetModule(select(i, ...), false)
		if CurrentModule then
			Modules[i] = CurrentModule
		else
			Modules[i] = {}
		end
	end
	
	return unpack(Modules)
end

E.ModuleLoadQueue = {}
function E:QueueModuleAutoload(name)
	table.insert(E.ModuleLoadQueue, name)
end

function E:LoadModuleAutoloadQueue()
	for k, v in pairs(E.ModuleLoadQueue) do
		E:InitializeModule(v)
	end
end

E.InitSettings = {}
function E:AddSettingsModule(object)
	table.insert(E.InitSettings, object)
end

function E:InitSettingsModules()
	for k,v in pairs(E.InitSettings) do
		v:Init()
	end
end

function E:MainMenuMicroButton_PositionAlert(alert)
	
	local OffsetX, OffsetY = 0

	--[[if ( alert.MicroButton:GetRight() + (alert:GetWidth() / 2) > E.Parent:GetRight() ) then
		alert:ClearAllPoints();
		alert:SetPoint("BOTTOMRIGHT", alert.MicroButton, "TOPRIGHT", 16, 20);
		alert.Arrow:ClearAllPoints();
		alert.Arrow:SetPoint("TOPRIGHT", alert, "BOTTOMRIGHT", -4, 4);
	else
		alert:ClearAllPoints();
		alert:SetPoint("BOTTOM", alert.MicroButton, "TOP", 0, 20);
		alert.Arrow:ClearAllPoints();
		alert.Arrow:SetPoint("TOP", alert, "BOTTOM", 0, 4);
	end
	
	-- /run _G["CollectionsMicroButtonAlert"]:ClearAllPoints(); _G["CollectionsMicroButtonAlert"]:SetPoint("CENTER", _G["CollectionsMicroButtonAlert"].MicroButton, "CENTER", 0,0)
	
	if ( alert.MicroButton:GetTop() + (alert:GetHeight() / 2) > E.Parent:GetTop() ) then
		alert:ClearAllPoints();
		alert:SetPoint("BOTTOMRIGHT", alert.MicroButton, "TOPRIGHT", 16, -20);
		alert.Arrow:ClearAllPoints();
		alert.Arrow:SetPoint("TOPRIGHT", alert, "BOTTOMRIGHT", -4, -400);
	else]]
		alert:ClearAllPoints();
		alert:SetPoint("TOP", alert.MicroButton, "BOTTOM", 0, -18);
		alert.Arrow:ClearAllPoints();
		alert.Arrow:SetPoint("BOTTOM", alert, "TOP", 0, 0);
		E:MicroMenuButton_SetAlertArrowTexCoord(alert, {0.78515625,0.99218750,0.58789063,0.54687500})
		-- <TexCoords left="0.78515625" right="0.99218750" top="0.54687500" bottom="0.58789063"/>
	--end
	
	if ( alert.MicroButton:GetLeft() + (alert:GetWidth() / 2) > E.Parent:GetLeft() ) then
		-- E:PushFrame()
		if alert:GetLeft() < 0 then
			E:PushFrame(alert, alert:GetLeft() * -1, 0)
			E:PushFrame(alert.Arrow, alert:GetLeft(), 0)
		end
	end
end
	
function E:MicroMenuButton_SetAlertArrowTexCoord(alert, texcoord)
	local kids = { alert.Arrow:GetRegions() };

	for _, child in ipairs(kids) do
		child:SetTexCoord(texcoord[1],texcoord[2],texcoord[3],texcoord[4])
	end
end

function E:ResizeEParent(state)
	if state == "original" then
		E.Parent:SetSize(UIParent:GetWidth(), UIParent:GetHeight())
	else
		E.Parent:SetSize(UIParent:GetWidth(), UIParent:GetHeight() - OrderHallCommandBar:GetHeight())
	end
end

function E:HandleCommandBar()
	OrderHallCommandBar:HookScript("OnShow", function() E:ResizeEParent("new") end)
	OrderHallCommandBar:HookScript("OnHide", function() E:ResizeEParent("original") end)
end

do
	if OrderHallCommandBar then
			E:HandleCommandBar()
		else
			local f = CreateFrame("Frame")
			f:RegisterEvent("ADDON_LOADED")
			f:SetScript("OnEvent", function(self, event, addon)
				if event == "ADDON_LOADED" and addon == "Blizzard_OrderHallUI" then
					if InCombatLockdown() then
						self:RegisterEvent("PLAYER_REGEN_ENABLED")
					else
						E:HandleCommandBar()
					end
					self:UnregisterEvent(event)
				elseif event == "PLAYER_REGEN_ENABLED" then
					E:HandleCommandBar()
					self:UnregisterEvent(event)
				end
			end)
		end
end

-- Init core modules here
-- This is because we need the config before everything else.
-- OnInit is the earliest point where we can do stuff with the profiles
-- ArtLib is dependent on this, since we change the 3D world font. This has to happen as soon as possible.
function E:OnInitialize()
	CO = E:GetModule("Config", true)
	E:GetModule("ArtLib", true)
	E:InitSettingsModules()
end

function E:OnEnable()
	
	Core 			= E:GetModule("Core", true)
	Minimap 		= E:GetModule("Minimap", true)
	Worldmap 		= E:GetModule("Worldmap", true)
	Chat 			= E:GetModule("Chat", true)
	Tooltip 		= E:GetModule("Tooltip", true)
	Unitframes 		= E:GetModule("Unitframes", true)
	Auras 			= E:GetModule("Auras", true)
	Bar_Auras 		= E:GetModule("Bar_Auras", true)
	Bar_Experience 	= E:GetModule("Bar_Experience", true)
	Bar_Cast 		= E:GetModule("Bar_Cast", true)
	Layout			= E:GetModule("Layout", true)
	AB				= E:GetModule("Actionbars", true)
	B				= E:GetModule("Blizzard", true)
	-- PO 			= E:GetModule("Performance_Optimizer", true)
	
	-- This is responsible for loading all kinds of plug-ins. We can add plug-ins to the queue via:
	-- Module.Autoload = true
	E:LoadModuleAutoloadQueue()
	
	B:RemoveBlizzard()
	CO:UpdateAllGroups()
	
	GameTooltipStatusBar.text = GameTooltipStatusBar:CreateFontString(nil, "OVERLAY")
	E:InitializeFontFrame(GameTooltipStatusBar.text, "OVERLAY", "FRIZQT__.TTF", 12, {1,1,1}, 1, {0,0}, "10101", 200, 100, GameTooltipStatusBar, "CENTER", {0,0})

	

	hooksecurefunc("MicroButtonAlert_OnShow", function(...) E:MainMenuMicroButton_RepositionAlerts() end)
	
	------------------------------------------------------------------------
	-- Prevent display of LUA-Errors, since the Beta API seems unstable
	------------------------------------------------------------------------
	
		ScriptErrorsFrame:SetScript("OnShow", function(self, ...)
			if not CO.db.profile.LUAErrors then
				self:Hide()
				E:print("LUA-Error received!")
			end
		end)
	-- print("\124Hmylinktype:myfunc\124h\124T".."Click to show"..":16\124t\124h") 
	------------------------------------------------------------------------
		
	ObjectiveTrackerFrame:SetHeight(ObjectiveTrackerFrame:GetHeight()) -- If we don't set this, there's basically just the header
	E:CreateMover(ObjectiveTrackerFrame, "Objective Tracker", "TOPRIGHT", ObjectiveTrackerFrame:GetWidth() + 25, 250)
	
	if E:IsLegionClient() then
		E:RegisterEvents(E.E, "UNIT_POWER", "RUNE_POWER_UPDATE", "UNIT_DISPLAYPOWER", "PLAYER_SPECIALIZATION_CHANGED", "SPELLS_CHANGED")
	else
		E:RegisterEvents(E.E, "UNIT_POWER_UPDATE", "RUNE_POWER_UPDATE", "UNIT_DISPLAYPOWER", "PLAYER_SPECIALIZATION_CHANGED", "SPELLS_CHANGED")
	end
	
	E:LoadMoverPositions()
	
	E.InitComplete = true
end