--[[
Name: Prat_ChatLink
Revision: $Revision: 20077 $
Author(s): Krtek (krtek4@gmail.com)
Inspired by: Cirk's Chatmanager by Cirk
             ChatLink by Yrys
Website: http://www.wowace.com/files/index.php?path=Prat/
Documentation: http://www.wowace.com/wiki/Prat/Integrated_Modules#ChatLink
SVN: http://svn.wowace.com/wowace/trunk/Prat/
Description: Module for Prat that shows item links in chat channels.
Dependencies: Prat
]]

local L = AceLibrary("AceLocale-2.2"):new("PratChatLink")

L:RegisterTranslations("enUS", function() return {
    ["ChatLink"] = true,
    ["Chat channel item link options."] = true,
    ["ChatManager"] = true,
    ["Toggle sending items in Cirk\" ChatManager format."] = true,
    ["Toggle sending items in ChatLink format."] = true,
    ["Toggle"] = true,
    ["Toggle the module on and off."] = true,
} end)

L:RegisterTranslations("zhCN", function() return {
	["ChatLink"] = "聊天链接",
	["Chat channel item link options."] = "聊天频道物品链接选项。",
	["ChatManager"] = "聊天管理",
	["Toggle sending items in Cirk\" ChatManager format."] = "切换以 Cirk\" 聊天管理模式发送物品。",
	["Toggle sending items in ChatLink format."] = "切换聊天链接物品发送格式。",
	["Toggle"] = "切换",
	["Toggle the module on and off."] = "切换此功能的打开与关闭。",
} end)


L:RegisterTranslations("koKR", function() return {
    ["ChatLink"] = "대화링크",
    ["Chat channel item link options."] = "대화 채널 아이템 링크 설정입니다.",
--    ["ChatManager"] = true,
    ["Toggle sending items in Cirk\" ChatManager format."] = "Cirk\" Chatmanager 형식으로 아이템 보내기를 전환합니다.",
    ["Toggle sending items in ChatLink format."] = "ChatLink 형식으로 아이템 보내기를 전환합니다.",
    ["Toggle"] = "전환",
    ["Toggle the module on and off."] = "모듈 켜고 끄기를 전환합니다.",
} end)

L:RegisterTranslations("zhTW", function() return {
    ["ChatLink"] = "聊天鏈結",
    ["Chat channel item link options."] = "聊天頻道物品鏈結選項。",
    ["ChatManager"] = "聊天管理",
    ["Toggle sending items in Cirk\" ChatManager format."] = "切換為 Cirk\" ChatManager 格式。",
    ["Toggle sending items in ChatLink format."] = "切換為 ChatLink 格式。",
    ["Toggle"] = "切換",
    ["Toggle the module on and off."] = "切換打開或關閉此模組。",
} end)

	
Prat_ChatLink = Prat:NewModule("chatlink")

function Prat_ChatLink:OnInitialize()
    self.db = Prat:AcquireDBNamespace("ChatLink")
    Prat:RegisterDefaults("ChatLink", "profile", {
        on = false,
        clink = true,
        chatmanager = false,
    })
    
    self.db.profile.chatmanager = false
    self.db.profile.clink = true
    
    Prat.Options.args.chatlink = {
        name = L["ChatLink"],
        desc = L["Chat channel item link options."],
        type = "group",
        args = {
            cm = {
                name = L["ChatManager"],
                desc = L["Toggle sending items in Cirk\" ChatManager format."],
                type = "toggle",
                disabled = function() return true end,
                get = function() return self.db.profile.chatmanager end,
                set = function(v) self.db.profile.clink = not v;  self.db.profile.chatmanager = v end
            },
            clink = {
                name = L["ChatLink"],
                desc = L["Toggle sending items in ChatLink format."],
                type = "toggle",
                get = function() return self.db.profile.clink end,
                set = function(v) self.db.profile.clink = v;  self.db.profile.chatmanager = not v end
            },
            toggle = {
                name = L["Toggle"],
                desc = L["Toggle the module on and off."],
                type = "toggle",
                order = 200,
                get = function() return self.db.profile.on end,
                set = function(v) self.db.profile.on = Prat:ToggleModuleActive("chatlink") end
            },
        }
        
    }

    --    Prat:ToggleModuleActive("chatlink", false)
end

function Prat_ChatLink:OnEnable()
    for i=1,NUM_CHAT_WINDOWS do
        self:Hook(getglobal("ChatFrame"..i), "AddMessage", true)
    end

    self:Hook("SendChatMessage", true)
end

-- Hook
function Prat_ChatLink:AddMessage(frame, text, ...)
    text = Prat_ChatLink:ProcessText (text)
    self.hooks[frame].AddMessage(frame, text, ...)
end

function Prat_ChatLink:SendChatMessage(msg, chatType, language, channel)
    if msg and (chatType == "CHANNEL") then
        local _, chanName = GetChannelName(channel)
        if chanName and
            not string.find (chanName, "General - ") and
            not string.find (chanName, "Trade - ") and
            not string.find (chanName, "LookingForGroup") and
            not string.find (chanName, "LocaleDefense - ") and
            not string.find (chanName, "WorldDefense")
        then
            msg = Prat_ChatLink:CreateLink(msg);
        end
    end
    self.hooks.SendChatMessage(msg, chatType, language, channel)
end

-- Utility Function
function Prat_ChatLink:ProcessText(text)
    if (self.db.profile.clink) then 
		return self:ChatLink_Decompose(text)
	end

    if text then
        -- Chatmanager [Thick Furry Mane]{4583:0:0:0}
        text = Prat_ChatLink:DecomposeCMLink(text, "%[([^%[^%]]-)%]{(%d+):(%d+):(%d+):(%d+)}(\b*)")
        
        -- Code from ChatLink
        
		text = string.gsub (text, "{CLINK:item:(%x+):(%d-:%d-:%d-:%d-:%d-:%d-:%d-:%d-):([^}]-)}", "|c%1|Hitem:%2|h[%3]|h|r")
		text = string.gsub (text, "{CLINK:enchant:(%x+):(%d-):([^}]-)}", "|c%1|Henchant:%2|h[%3]|h|r")
		-- For backward compatibility (yeah, I should have done it before...).
		text = string.gsub (text, "{CLINK:(%x+):(%d-:%d-:%d-:%d-:%d-:%d-:%d-:%d-):([^}]-)}", "|c%1|Hitem:%2|h[%3]|h|r")

		-- Forward compatibility, for future clink structure changes.
		text = string.gsub (text, "{CLINK(%d):%[?([^:}%]]-)%]?:([^:}]-)[^}]-}", "%2")   
		
    	return text
    end
end

function Prat_ChatLink:CreateLink(link)
    local pattern = "|c(%x+)|Hitem:(%d+):(%d+):(%d+):(%d+)|h%[(.-)%]|h|r"
    if (self.db.profile.clink) then 
		return self:ChatLink_Compose(link)
    elseif (self.db.profile.chatmanager) then return Prat_ChatLink:CreateCMLink(link, pattern)
    else return link end
end

-- Inspired from Cirk"s Chatmanager
local _rarityConvertToColor = {}
local _rarityLookupByColor = {}

for rarity = 0, 6 do
    local _, _, _, itemColor = GetItemQualityColor(rarity);
    if (itemColor) then
        _rarityConvertToColor[rarity] = itemColor;
        _rarityLookupByColor[string.sub(itemColor, 3)] = rarity;
    end
end

function Prat_ChatLink:DecomposeCMLink(link, pattern)
    local function gsubDecomposeCMLink(name, i1, i2, i3, i4, rS)
        local itemString = "item:"..i1..":"..i2..":"..i3..":"..i4;
        local itemName, itemLink, itemRarity = GetItemInfo(itemString);
        if (itemName and itemLink and itemRarity) then
            local itemColor = _rarityConvertToColor[tonumber(itemRarity)];
            if (not itemColor) then
                itemColor = "";
            end
            return itemColor.."|H"..itemLink.."|h["..itemName.."]|h|r";
        end
        itemRarity = string.len(rS) - 1;
        if (itemRarity >= 0) then
            local itemColor = _rarityConvertToColor[tonumber(itemRarity)];
            if (not itemColor) then
                itemColor = "";
            end
            return itemColor.."|H"..itemString.."|h["..name.."]|h|r";
        end
        return "|H"..itemString.."|h["..name.."]|h|r";
    end
    return string.gsub(link, pattern, gsubDecomposeCMLink)
end

function Prat_ChatLink:CreateCMLink(link, pattern)
    local function gsubCMLink(cS, i1, i2, i3, i4, name)
        local itemString = "item:"..i1..":"..i2..":"..i3..":"..i4;
        local _, _, itemRarity = GetItemInfo(itemString);
        if (not itemRarity) then
            -- Perform reverse color lookup to get rarity instead
            itemRarity = _rarityLookupByColor[cS];
        end
        if (itemRarity) then
            return "["..name.."]{"..i1..":"..i2..":"..i3..":"..i4.."}"..string.rep("\b", tonumber(itemRarity) + 1);
        end
        return "["..name.."]{"..i1..":"..i2..":"..i3..":"..i4.."}";
    end
    return string.gsub(link, pattern, gsubCMLink)
end


-- CREDIT TO: Yrys - Hellscream, author of ChatLink, the following code copied verbatim

-- Turn CLINKs into normal item and enchant links.
function Prat_ChatLink:ChatLink_Decompose (chatstring)
	if chatstring then
		chatstring = string.gsub (chatstring, "{CLINK:item:(%x+):(%d-:%d-:%d-:%d-:%d-:%d-:%d-:%d-):([^}]-)}", "|c%1|Hitem:%2|h[%3]|h|r")
		chatstring = string.gsub (chatstring, "{CLINK:enchant:(%x+):(%d-):([^}]-)}", "|c%1|Henchant:%2|h[%3]|h|r")
		-- For backward compatibility (yeah, I should have done it before...).
		chatstring = string.gsub (chatstring, "{CLINK:(%x+):(%d-:%d-:%d-:%d-:%d-:%d-:%d-:%d-):([^}]-)}", "|c%1|Hitem:%2|h[%3]|h|r")

		-- Forward compatibility, for future clink structure changes.
		chatstring = string.gsub (chatstring, "{CLINK(%d):%[?([^:}%]]-)%]?:([^:}]-)[^}]-}", "%2")
	end
	return chatstring
end



-- Turn item and enchant links into CLINKs.
function Prat_ChatLink:ChatLink_Compose (chatstring)
	if chatstring then
--		1.10 item links: to possibly be reactivated in a future version.
--		chatstring = string.gsub (chatstring, "|c(%x+)|H(item):(%d-):(%d-):(%d-):(%d-)|h%[([^%]]-)%]|h|r", "{CLINK:%2:%1:%3:%4:%5:%6:%7}")
--		Old item links: backward compatibility.
		chatstring = string.gsub (chatstring, "|c(%x+)|Hitem:(%d-:%d-:%d-:%d-:%d-:%d-:%d-:%d-)|h%[([^%]]-)%]|h|r", "{CLINK:%1:%2:%3}")
		chatstring = string.gsub (chatstring, "|c(%x+)|H(enchant):(%d-)|h%[([^%]]-)%]|h|r", "{CLINK:%2:%1:%3:%4}")
	end
	return chatstring
end

