local E, L, V, P, G = unpack(ElvUI);
local mPlugin = "mMediaTag"
local addon, ns = ...

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

local function mMediaTagKeys(event, text, channelIndex)
    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

local function OnEvent(self, event, ...)
	if E.db[mPlugin].mMythicPlusTools.keys and (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
		local text , _, _, _, _, _, _, channelIndex = ...

		if text then
			text = string.lower(text)
			mMT:mMediaTagKeys(event, text, channelIndex)
		end
	end
end

local function mKeystoneToChatOptions()
    E.Options.args.mMediaTag.args.general.args.myticplustools.args = {
        keystontochat = {
            order = 10,
            type = 'toggle',
            name = L["Send Keyston to Chat"],
            desc = L["Sends your Keyston to Chat, wen ther ist The Keyword !key or !keys"],
            get = function(info)
                return E.db[mPlugin].mMythicPlusTools.keys
            end,
            set = function(info, value)
                E.db[mPlugin].mMythicPlusTools.keys = value
            end,
        },
    }
end

table.insert(ns.Config, mKeystoneToChatOptions)
local mKeystoneToChat = CreateFrame("FRAME")
mKeystoneToChat:RegisterEvent("CHAT_MSG_PARTY")
mKeystoneToChat:RegisterEvent("CHAT_MSG_PARTY_LEADER")
mKeystoneToChat:RegisterEvent("CHAT_MSG_RAID")
mKeystoneToChat:RegisterEvent("CHAT_MSG_RAID_LEADER")
mKeystoneToChat:RegisterEvent("CHAT_MSG_GUILD")
mKeystoneToChat:RegisterEvent("CHAT_MSG_COMMUNITIES_CHANNEL")
mKeystoneToChat:SetScript("OnEvent", OnEvent)
mKeystoneToChat:Show()