local E, L, V, P, G = unpack(ElvUI);
local mPlugin = "mMediaTag"
local mMT = E:GetModule(mPlugin);
local DT = E:GetModule("DataTexts");
local addon, ns = ...

--Lua functions
local tinsert = tinsert
local format = format
local strjoin = strjoin
local wipe = wipe

--WoW API / Variables
local _G = _G
local C_ChallengeMode = C_ChallengeMode
local C_MythicPlus = C_MythicPlus
local IsInInstance = IsInInstance
local InCombatLockdown = InCombatLockdown
local IsAddOnLoaded = IsAddOnLoaded

--Variables
local displayString, lastPanel = ""
local mText = L["Game Menu"]
local menuList = {}
local menuFrame = CreateFrame('Frame', 'mSystemMenu', E.UIParent, 'BackdropTemplate')
menuFrame:SetTemplate("Transparent", true)

local function mColor(color)
	local mSetting = E.db[mPlugin].mMenuColor 
	if mSetting then
		if color == 1 then
			return ns.mColor1
		elseif color == 2 then
			return ns.mColor2
		elseif color == 3 then
			return ns.mColor3
		elseif color == 4 then
			return ns.mColor4
		elseif color == 5 then
			return ns.mColor5
		elseif color == 6 then
			return ns.mColor6
		elseif color == 7 then
			return ns.mColor7
		end
	else
		return ns.mColor1
	end
end


local function OnEvent(self)
	if E.db[mPlugin].InstancInfoName then 
		local inInstance, _ = IsInInstance()
		if inInstance then
			if C_MythicPlus.IsMythicPlusActive() and (C_ChallengeMode.GetActiveChallengeMapID() ~= nil) then
				self.text:SetText(format("%s +%s", mMT:DungeonInfoName(), mMT:MythPlusDifficultyShort()))
			else
				self.text:SetText(mMT:DungeonInfoName())
			end
		else
			self.text:SetFormattedText(displayString, mText)
		end
	else
		self.text:SetFormattedText(displayString, mText)
	end
	lastPanel = self
end

local function OnClick(self, button)
	DT.tooltip:Hide()
	if button == "LeftButton" then
		wipe(menuList)--menuList = {}
		menuList = {
			{text = CHARACTER_BUTTON, isTitle = false, color = mColor(2),
			func = function() ToggleCharacter("PaperDollFrame") end},
			{text = SPELLBOOK_ABILITIES_BUTTON, isTitle = false, color = mColor(2),
			func = function() if not SpellBookFrame:IsShown() then ShowUIPanel(SpellBookFrame) else HideUIPanel(SpellBookFrame) end end},
			{text = TALENTS_BUTTON, isTitle = false, color = mColor(2),
				func = function()
					if not PlayerTalentFrame then
						TalentFrame_LoadUI()
					end
					
					if not PlayerTalentFrame:IsShown() then
						ShowUIPanel(PlayerTalentFrame)
					else
						HideUIPanel(PlayerTalentFrame)
					end
			end},
			{text = ACHIEVEMENT_BUTTON, isTitle = false, color = mColor(2),
			func = function() ToggleAchievementFrame() end},
			
			{text = "", isTitle = true, func = function() end},
			
			{text = GARRISON_LANDING_PAGE_TITLE, isTitle = false, color = mColor(7),
			func = function() GarrisonLandingPageMinimapButton_OnClick() end},
			{text = COLLECTIONS, isTitle = false, color = mColor(7),
				func = function()
					ToggleCollectionsJournal()
			end},
			
			{text = "", isTitle = true, func = function() end},
			
			{text = TIMEMANAGER_TITLE, isTitle = false, color = mColor(1),
			func = function() ToggleFrame(TimeManagerFrame) end},
			{text = L["Calendar"], isTitle = false, color = mColor(1),
			func = function() GameTimeFrame:Click() end},
			
			{text = "", isTitle = true, func = function() end},
			
			{text = SOCIAL_BUTTON, isTitle = false, color = mColor(6),
			func = function() ToggleFriendsFrame() end},
			{text = ACHIEVEMENTS_GUILD_TAB, isTitle = false, color = mColor(6),
			func = function() ToggleGuildFrame() end},
			
			{text = "", isTitle = true, func = function() end},
			
			{text = LFG_TITLE, isTitle = false, color = mColor(7),
			func = function() ToggleLFDParentFrame(); end},
			{text = ENCOUNTER_JOURNAL, isTitle = false, color = mColor(7),
			func = function() if not IsAddOnLoaded("Blizzard_EncounterJournal") then EncounterJournal_LoadUI(); end ToggleFrame(EncounterJournal) end},
			
			{text = "", isTitle = true, func = function() end},
			
			
			{text = "ElvUI", isTitle = false, color = mColor(4),
				func = function() 
					if InCombatLockdown() then _G.UIErrorsFrame:AddMessage(E.InfoColor.._G.ERR_NOT_IN_COMBAT) return end
					E:ToggleOptionsUI()
			end},
			
			{text = "", isTitle = true, func = function() end},
			
			{text = MAINMENU_BUTTON, isTitle = false, color = mColor(1),
				func = function()
					if ( not GameMenuFrame:IsShown() ) then
						if ( VideoOptionsFrame:IsShown() ) then
							VideoOptionsFrameCancel:Click();
						elseif ( AudioOptionsFrame:IsShown() ) then
							AudioOptionsFrameCancel:Click();
						elseif ( InterfaceOptionsFrame:IsShown() ) then
							InterfaceOptionsFrameCancel:Click();
						end
						CloseMenus();
						CloseAllWindows()
						ShowUIPanel(GameMenuFrame);
					else
						HideUIPanel(GameMenuFrame);
						MainMenuMicroButton_SetNormal();
					end
			end},
			
			{text = "", isTitle = true, func = function() end},
			
			{text = BLIZZARD_STORE, isTitle = false, color = mColor(5), func = function() StoreMicroButton:Click() end},
			{text = HELP_BUTTON, isTitle = false, color = mColor(5), func = function() ToggleHelpFrame() end}
		}
		mMT:mDropDown(menuList, menuFrame, E.db[mPlugin].mMenuUp, 160)
	else
		ToggleLFDParentFrame()
	end
end

local function OnEnter(self)
	local nhc, hc, myth, mythp, other, titel, tip = mMT:mColorDatatext()
	
	DT.tooltip:AddLine(mText)
	if E.db[mPlugin].InstancInfoToolTip then
		local mInctanceInfo = mMT:InctanceInfo()
		if mInctanceInfo then
			DT.tooltip:AddLine(" ")
			DT.tooltip:AddLine(mInctanceInfo[1] or "-")
			DT.tooltip:AddLine(mInctanceInfo[2] or "-")
			DT.tooltip:AddLine(mInctanceInfo[3] or "-")
		end
		
		local inInstance, _ = IsInInstance()
		if inInstance then
			local infoinInstance = mMT:DungeonInfo()
			DT.tooltip:AddLine(" ")
			DT.tooltip:AddLine(infoinInstance[1] or "-")
			DT.tooltip:AddLine(infoinInstance[2] or "-")
			DT.tooltip:AddLine(infoinInstance[3] or "-")
		end
		
		if C_MythicPlus.IsMythicPlusActive() and (C_ChallengeMode.GetActiveChallengeMapID() ~= nil) then
			local infoMythicPlus = mMT:MythicPlusDungeon()
			DT.tooltip:AddLine(" ")
			DT.tooltip:AddLine(infoMythicPlus[1] or "-")
			DT.tooltip:AddLine(infoMythicPlus[2] or "-")
		end
		
		if E.db[mPlugin].SAchievement0 then
			DT.tooltip:AddLine(" ")
			local infoAchievement0 = mMT:Achievement(0)
			DT.tooltip:AddLine(infoAchievement0[0])
			for i=1,8 do
				DT.tooltip:AddDoubleLine(infoAchievement0[i][1] or "-", infoAchievement0[i][2] or "-")
			end
		end
		
		if E.db[mPlugin].SAchievement10 then
			DT.tooltip:AddLine(" ")
			local infoAchievement10 = mMT:Achievement(10)
			DT.tooltip:AddLine(infoAchievement10[0])
			for i=1,8 do
				DT.tooltip:AddDoubleLine(infoAchievement10[i][1] or "-", infoAchievement10[i][2] or "-")
			end
		end
		
		if E.db[mPlugin].SAchievement15 then
			DT.tooltip:AddLine(" ")
			local infoAchievement15 = mMT:Achievement(15)
			DT.tooltip:AddLine(infoAchievement15[0])
			for i=1,8 do
				DT.tooltip:AddDoubleLine(infoAchievement15[i][1] or "-", infoAchievement15[i][2] or "-")
			end
		end
		
		if E.db[mPlugin].SKeystone then
			local key = mMT:OwenKeystone()
			if key then
				DT.tooltip:AddLine(" ")
				DT.tooltip:AddLine(key[1] or "-")
				DT.tooltip:AddLine(key[2] or "-")
			end 
			
		end
		
		if E.db[mPlugin].SAffix then
			local mAffixes = mMT:WeeklyAffixes()
			if mAffixes then
				DT.tooltip:AddLine(" ")
				if mAffixes[3] then
					DT.tooltip:AddLine(mAffixes[3])
				else
					DT.tooltip:AddLine(mAffixes[1])
					DT.tooltip:AddLine(mAffixes[2])
				end
			end
		end
		
		DT.tooltip:AddLine(" ")
	end
	
	DT.tooltip:AddDoubleLine(ns.mName, format("%sVer.|r %s%s|r" , titel, other, ns.mVersion))
	DT.tooltip:AddLine(" ")
	DT.tooltip:AddLine(format("%s %s%s|r", ns.LeftButtonIcon, tip, L["Click left to open the main menu."]))
	DT.tooltip:AddLine(format("%s %s%s|r", ns.RightButtonIcon, tip, L["Left click to open the menu."]))
	DT.tooltip:Show()
end

local function OnLeave(self)
	DT.tooltip:Hide()
end

local function ValueColorUpdate(hex)
	displayString = strjoin("", hex, "%s|r")
	
	if lastPanel ~= nil then
		OnEvent(lastPanel, "ELVUI_COLOR_UPDATE")
	end
end
E.valueColorUpdateFuncs[ValueColorUpdate] = true

DT:RegisterDatatext("Game Menu", nil, {"CHALLENGE_MODE_START", "CHALLENGE_MODE_COMPLETED", "PLAYER_ENTERING_WORLD", "UPDATE_INSTANCE_INFO"}, OnEvent, nil, OnClick, OnEnter, OnLeave, mText, ValueColorUpdate)