local E, L, V, P, G = unpack(ElvUI);
local mPlugin = "mMediaTag"
local mMT = E:GetModule(mPlugin);
local DT = E:GetModule("DataTexts");
local addon, ns = ...
local LSM = E.Libs.LSM
local _, unitClass = UnitClass('player')
local class = ElvUF.colors.class[unitClass]

function mMT:mCheckCombat()
    if InCombatLockdown() then
		_G.UIErrorsFrame:AddMessage(format("%s%s|r", ns.mColor5, _G.ERR_NOT_IN_COMBAT))
		print (format("%s%s|r", ns.mColor5, _G.ERR_NOT_IN_COMBAT))
	else
		return false
    end
end

function mMT:mSetColor(color)
    if color == "normal" then
        if E.db[mPlugin].mDock.normal.style == "class" then
            return class[1], class[2], class[3], E.db[mPlugin].mDock.nottification.a
        else
            return E.db[mPlugin].mDock.normal.r, E.db[mPlugin].mDock.normal.g, E.db[mPlugin].mDock.normal.b, E.db[mPlugin].mDock.normal.a
        end
    elseif color == "click" then
        if E.db[mPlugin].mDock.click.style == "class" then
            return class[1], class[2], class[3], E.db[mPlugin].mDock.nottification.a
        else
            return E.db[mPlugin].mDock.click.r, E.db[mPlugin].mDock.click.g, E.db[mPlugin].mDock.click.b, E.db[mPlugin].mDock.click.a
        end
    elseif color == "hover" then
        if E.db[mPlugin].mDock.hover.style == "class" then
            return class[1], class[2], class[3], E.db[mPlugin].mDock.nottification.a
        else
            return E.db[mPlugin].mDock.hover.r, E.db[mPlugin].mDock.hover.g, E.db[mPlugin].mDock.hover.b, E.db[mPlugin].mDock.hover.a
        end
    elseif color == "notifi" then
        if E.db[mPlugin].mDock.nottification.style == "class" then
            return class[1], class[2], class[3], E.db[mPlugin].mDock.nottification.a
        else
            return E.db[mPlugin].mDock.nottification.r, E.db[mPlugin].mDock.nottification.g, E.db[mPlugin].mDock.nottification.b, E.db[mPlugin].mDock.nottification.a
        end
    end
end

function mMT:mFade(self, FadeIn)
    if FadeIn then
        E:UIFrameFadeIn(self.mIcon, E.db[mPlugin].mDock.fadetime, E.db[mPlugin].mDock.normal.a, E.db[mPlugin].mDock.fadealpha)
    else
        E:UIFrameFadeOut(self.mIcon, E.db[mPlugin].mDock.fadetime, E.db[mPlugin].mDock.fadealpha, E.db[mPlugin].mDock.normal.a)
    end
end

local function SetUpIcon(self, notifi, text)
    if not self.loaded then
        self.loaded = true
        self.mIcon 	= self:CreateTexture(nil, "ARTWORK")
        self.mIcon:Point("CENTER")
    
        if notifi then
            self.mNotifications	= self:CreateTexture(nil, "ARTWORK")
            self.mNotifications:Point("TOPLEFT", 2, 2)
        end
    
        if text then
            self.mText = self:CreateFontString(self, "OVERLAY", "GameTooltipText")
            self.mText:SetFont(LSM:Fetch('font', E.db[mPlugin].mDock.font), E.db[mPlugin].mDock.fontSize or E.db["datatexts"]["fontSize"], E.db[mPlugin].mDock.fontflag  or E.db["actionbar"]["fontOutline"])
            self.mText:SetPoint("BOTTOMRIGHT", 2, 2)
        end
    end
end

local function UpdateIcon(self, notifi, texture)
    local xy = E.db[mPlugin].mDock.sizexy
    self:Size(xy, xy)
    self.mIcon:SetTexture(texture)
    self.mIcon:Size(xy, xy)

    if notifi then
        local nxy = E.db[mPlugin].mDock.nottification.size or 8
        self.mNotifications:SetTexture(E.db[mPlugin].mDock.textures.nottification.path)
        self.mNotifications:Size(nxy, nxy)
        self.mNotifications:SetVertexColor(mMT:mSetColor("notifi"))
        self.mNotifications:Hide()
    end

    self.hover 	= false
end

local function CheckWindow(self, option, leave, timer)
    if option then
        self.down 	= true
        self.mIcon:SetVertexColor(mMT:mSetColor("click"))
        if timer then
            self.CheckTimer = mMT:ScheduleRepeatingTimer(timer, 2, self)
        end
    else
        self.down 	= false
        self.mIcon:SetVertexColor(mMT:mSetColor("normal"))
    end

    if leave then
        mMT:mFade(self, false)
    end
end

local function mDownCheck(self)
    if self.down then
		self.mIcon:SetVertexColor(mMT:mSetColor("click"))
	else
        self.mIcon:SetVertexColor(mMT:mSetColor("hover"))
        mMT:mFade(self, true)
    end
end

local function mSetHover(self)
    local xy = E.db[mPlugin].mDock.sizexy
    self.hover 	= true
    self.mIcon:Size(xy+E.db[mPlugin].mDock.growsize, xy+E.db[mPlugin].mDock.growsize)
end

function mMT:mOnEvent(self, notifi, text, displayString, option, texture, timer)--xxxx
    SetUpIcon(self, notifi or false, text or false)
    UpdateIcon(self, notifi, texture)
    if text and displayString then
        self.mText:SetFormattedText(displayString, text)
    elseif text then
        self.mText:SetText(text)
    end

    if not self.CheckTimer then
        CheckWindow(self, option, false, timer)
    end
end

function mMT:mOnLeave(self, option)--xxxx
    local xy = E.db[mPlugin].mDock.sizexy
    CheckWindow(self, option, true)
    self.hover	= false
    self.mIcon:Size(xy, xy)
    if E.db[mPlugin].mDock.tip.enable then
        DT.tooltip:Hide()
    end
end

function mMT:mClick(self, timer)--xxxx
    if self.down then
		if self.hover then
			self.mIcon:SetVertexColor(mMT:mSetColor("hover"))
		else
			self.mIcon:SetVertexColor(mMT:mSetColor("normal"))
		end
		self.down	= false
		mMT:CancelTimer(self.CheckTimer)
	else
		self.mIcon:SetVertexColor(mMT:mSetColor("click"))
		self.down 	= true
		self.CheckTimer = mMT:ScheduleRepeatingTimer(timer, 2, self)
    end
end

function mMT:mOnEnter(self, text)--xxxx
    mDownCheck(self)
    mSetHover(self)

    if E.db[mPlugin].mDock.tip.enable and text then
		DT.tooltip:AddLine(text)
		DT.tooltip:Show()
	end
end


function mMT:DockTimerCheck(self, option, color, r, g, b, a)--xxxx
    if option then
        self.down 	= true
        if color then
            self.mIcon:SetVertexColor(r, g, b, a)
        else
            self.mIcon:SetVertexColor(mMT:mSetColor("click"))
        end
	else
        self.down 	= false
        if color then
            self.mIcon:SetVertexColor(r, g, b, a)
        else
            self.mIcon:SetVertexColor(mMT:mSetColor("normal"))
        end
        mMT:CancelTimer(self.CheckTimer)
	end
end

local function mCheckText(text)
    for index, value in ipairs({"!key", "!keys"}) do
        if text == value then
            return true
        end
    end
end

local function mCheckKey()
    for bag = 0, NUM_BAG_SLOTS do
        local numSlots = GetContainerNumSlots(bag)
        for slot = 1, numSlots do
            if C_Item.IsItemKeystoneByID(GetContainerItemID(bag, slot)) then
               return GetContainerItemLink(bag, slot)                          
            end
        end
    end
end

local function mGetChat(event)
    if event == "CHAT_MSG_GUILD" then
        return "GUILD"
    elseif event == "CHAT_MSG_PARTY" or event == "CHAT_MSG_PARTY_LEADER" then
        return "PARTY"
    elseif event == "CHAT_MSG_RAID" or event == "CHAT_MSG_RAID_LEADER" then
        return "RAID"
    elseif event == "CHAT_MSG_COMMUNITIES_CHANNEL" then
        return "CHANNEL"
    end
end

function mMT:mMediaTagKeys(event, text, channelIndex)
    if event == "CHAT_MSG_GUILD" or event == "CHAT_MSG_PARTY" or event == "CHAT_MSG_PARTY_LEADER" or event == "CHAT_MSG_RAID" or event == "CHAT_MSG_RAID_LEADER" or event == "CHAT_MSG_COMMUNITIES_CHANNEL"then
        if mCheckText(text) then
            local link = mCheckKey()

            if link then
                local chat = mGetChat(event)
                if chat then
                    if channelIndex then
                        SendChatMessage(link, chat, nil, channelIndex)
                    else
                        SendChatMessage(link, chat)
                    end
                end
            end
        end
    end
end

function mMT:InctanceInfo()
    local DungeonID = GetDungeonDifficultyID()
	local RaidID = GetRaidDifficultyID()
	local DungeonName, _, _, _, _, _, _ = GetDifficultyInfo(DungeonID)
	local RaidName, _, _, _, _, _, _ = GetDifficultyInfo(RaidID)
    local text = {}
    local nhc, hc, myth, other, titel = E.db[mPlugin].mDataText.colornhc.hex, E.db[mPlugin].mDataText.colorhc.hex, E.db[mPlugin].mDataText.colormyth.hex, E.db[mPlugin].mDataText.colorother.hex, E.db[mPlugin].mDataText.colortitel.hex
   
    table.insert(text, 1, format("%s%s|r", titel, L["Instancoptions"]))

    if DungeonID == 1 then
        table.insert(text, 2, format("%s%s:|r %s%s|r", other, DUNGEON_DIFFICULTY, nhc, DungeonName))
    elseif DungeonID == 2 then
        table.insert(text, 2, format("%s%s:|r %s%s|r", other, DUNGEON_DIFFICULTY, hc, DungeonName))
    elseif DungeonID == 23 then
        table.insert(text, 2, format("%s%s:|r %s%s|r", other, DUNGEON_DIFFICULTY, myth, DungeonName))
    else
        table.insert(text, 2, format("%s%s:|r %s%s|r", other, DUNGEON_DIFFICULTY, other, DungeonName))
    end

    if RaidID == 14 then
        table.insert(text, 3, format("%s%s:|r %s%s|r", other, RAID_DIFFICULTY, nhc, RaidName))
    elseif RaidID == 15 then
        table.insert(text, 3, format("%s%s:|r %s%s|r", other, RAID_DIFFICULTY, hc, RaidName))
    elseif RaidID == 16 then
        table.insert(text, 3, format("%s%s:|r %s%s|r", other, RAID_DIFFICULTY, myth, RaidName))
    else
        table.insert(text, 3, format("%s%s:|r %s%s|r", other, RAID_DIFFICULTY, other, RaidName))
    end

    if text then 
        return text
    end
end

function mMT:WeeklyAffixes()
    local nhc, hc, myth, other, titel = E.db[mPlugin].mDataText.colornhc.hex, E.db[mPlugin].mDataText.colorhc.hex, E.db[mPlugin].mDataText.colormyth.hex, E.db[mPlugin].mDataText.colorother.hex, E.db[mPlugin].mDataText.colortitel.hex
    local AffixText = nil
    local text = {}

	if (date("%u") == "2") or (date("%u") == "3") and not E.db[mPlugin].mSavedAffixes.reset then
		E.db[mPlugin].mSavedAffixes.affixes = nil
		E.db[mPlugin].mSavedAffixes.reset = true
	elseif (date("%u") ~= "2") and (date("%u") ~= "3") then
		E.db[mPlugin].mSavedAffixes.reset = false
	end

	if (date("%u") ~= "2") and (date("%u") ~= "3") and (tonumber(E.db[mPlugin].mSavedAffixes.day) >= (tonumber(date("%j")) +5)) then
		affixes = E.db[mPlugin].mSavedAffixes.affixes
		if (affixes) == nil then
			affixes = C_MythicPlus.GetCurrentAffixes()
			if not (affixes) == nil then
				E.db[mPlugin].mSavedAffixes.affixes = affixes
			end
		end
	else
		affixes = C_MythicPlus.GetCurrentAffixes()
		E.db[mPlugin].mSavedAffixes.affixes = affixes
		E.db[mPlugin].mSavedAffixes.day = date("%j")
	end

	if (affixes) then
		for i, affix in ipairs(affixes) do
			local name, _, _ = C_ChallengeMode.GetAffixInfo(affix.id)
			if AffixText == nil then
				AffixText = name
			else
				AffixText = format("%s, %s", AffixText, name)
			end
		end
	else
		affixes = C_MythicPlus.GetCurrentAffixes()
		if not (affixes) == nil then
			E.db[mPlugin].mSavedAffixes.affixes = affixes
		end
	end

	if AffixText ~= nil then
		local seasonID = C_MythicPlus.GetCurrentSeason()
		if seasonID <= 0 then
			seasonID = E.db[mPlugin].mSavedAffixes.season
		end
		
		if seasonID >= 1 then
            E.db[mPlugin].mSavedAffixes.season = seasonID
            
            table.insert(text, 1, format("%s%s|r", titel,  L["This Week Affix"]))
            table.insert(text, 2, format("%s%s|r", other, AffixText))
            
            if text then
                return text
            end
        else
            table.insert(text, 3, format("%s%s|n%s|r", ns.mColor5, L["Saisson has not started yet."], L["ERROR! Please open the Mytisch+ window, LFG Tool or Reload UI!"]))
			return text
		end
    else
        table.insert(text, 3, format(L["%sERROR! Please open the Mytisch+ window, LFG Tool or Reload UI!|r"], ns.mColor5))
		return text
	end
end

function mMT:OwenKeystone()
    local keyStoneLevel , keyStoneLevelMax = C_MythicPlus.GetOwnedKeystoneLevel(), 20

    if keyStoneLevel then
        local challengeMapID = C_MythicPlus.GetOwnedKeystoneChallengeMapID()
        local name, id, timeLimit, texture, backgroundTexture = C_ChallengeMode.GetMapUIInfo(challengeMapID)
        local r, g, b = ElvUF:ColorGradient(keyStoneLevel, keyStoneLevelMax, 0.33, 0.59, 0.33, 0.65, 0.63, 0.35, 0.69, 0.31, 0.31)
        local nhc, hc, myth, other, titel = E.db[mPlugin].mDataText.colornhc.hex, E.db[mPlugin].mDataText.colorhc.hex, E.db[mPlugin].mDataText.colormyth.hex, E.db[mPlugin].mDataText.colorother.hex, E.db[mPlugin].mDataText.colortitel.hex
        local text = {}

        if keyStoneLevel then
            table.insert(text, 1, format("%s%s|r", titel, L["Mythic Plus Keystone"]))
            table.insert(text, 2, format("%s%s: |r %s%s|r%s +%s|r", ns.mColor1, L["Keystone"], myth, name, E:RGBToHex(r, g, b), keyStoneLevel))
        end

        if text then
            return text
        end
    end
end