---------------------------------------------------------------------------------
--
-- Prat - A framework for World of Warcraft chat mods
--
-- Copyright (C) 2006-2007  Prat Development Team
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to:
--
-- Free Software Foundation, Inc., 
-- 51 Franklin Street, Fifth Floor, 
-- Boston, MA  02110-1301, USA.
--
--
-------------------------------------------------------------------------------



--[[
Name: PratPopupMessage
Revision: $Revision: 27189 $
Author(s): Sylvanaar
Inspired by: CleanChat
Website: http://www.wowace.com/files/index.php?path=Prat/
Documentation: http://www.wowace.com/wiki/Prat/Integrated_Modules#PopupMessage
SVN: http://svn.wowace.com/wowace/trunk/Prat/
Description: Module for Prat that displays chat with your name in a pop up window
Dependencies: Prat
]]

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

L:RegisterTranslations("enUS", function() return {
    ["PopupMessage"] = true,
    ["Shows messages with your name in a popup."] = true,
    ["Set Separately"] = true,
    ["Toggle setting options separately for each chat window."] = true,
    ["Show Popups"] = true,
    ["Show Popups for each window."] = true,
    ["Chat%dPopupShow"] = true,
    ["Show popups on and off for chat window %d."] = true,
    ["Show All Popups"] = true,
    ["Show Popups for all chat windows."] = true,
    ["An alternate name to show in popups."] = true,
    ["Add Nickname"] = true,
    ["Remove Nickname"] = true,
    ["Clear Nickname"] = true,
 	["Use SCT Message"] = true,
	["Show the text as an SCT message instead of in its own frame"] = true,
    ["Toggle"] = true,
    ["Toggle the module on and off."] = true,

    ["show_name"] = "Show",
    ["show_desc"] = "Toggle showing timestamp settings for each window.",
    ["show_perframename"] = "Chat%dPopupShow",
    ["show_perframedesc"] = "Toggles popups on and off for chat window %d.",
    ["showall_name"] = "Show All Popups",
    ["showall_desc"] = "Show Popups for all chat windows.",
    ["usesct_name"] = "Use SCT Message",
    ["usesct_desc"] = "Show the text as an SCT message instead of in its own frame",
} end)

L:RegisterTranslations("frFR", function() return {
    ["PopupMessage"] = "Alerte pseudo",
    ["Shows messages with your name in a popup."] = "Affiche dans une fenêtre les messages qui contiennent votre nom.",
    ["Set Separately"] = "Régler séparément",
    ["Toggle setting options separately for each chat window."] = "Règle les options séparément pour chaque fenêtre de chat.",
    ["Show Popups"] = "Fenêtre flottante",
    ["Show Popups for each window."] = "Afficher les fenêtres flottantes pour chaque fenêtre de discussion.",
    ["Chat%dPopupShow"] = "Fenêtre %d",
    ["Show popups on and off for chat window %d."] = "Afficher les fenêtres flottantes pour la fenêtre %d.",
    ["Show All Popups"] = "Afficher toutes les fenêtres flottantes",
    ["Show Popups for all chat windows."] = "Afficher les fenêtres flottantes pour toutes les fenêtres de chat.",
    ["An alternate name to show in popups."] = "Un nom secondaire pour lequel afficher les alertes.",
    ["Add Nickname"] = "Ajouter un pseudo",
    ["Remove Nickname"] = "Supprimer un pseudo",
    ["Clear Nickname"] = "Vider les pseudos",
 	["Use SCT Message"] = "Utiliser les messages de SCT",
	["Show the text as an SCT message instead of in its own frame"] = "Affiche le texte comme un message SCT",

    ["show_name"] = "Afficher",
    ["show_desc"] = "Afficher l'heure pour chaque fenêtre.",
	["show_perframename"] = "Fenêtre %d",
    ["show_perframedesc"] = "Affiche/masque les fenêtres flottantes pour la fenêtre %d.",
} end)

-- L:RegisterTranslations("zhCN", function() return {
--     ["PopupMessage"] = "弹出消息",
--     ["Shows messages with your name in a popup."] = "在弹出窗口中显示包含自己名字的消息.",
-- 	["Toggle"] = "切换",
-- 	["Toggle the module on and off."] = "切换此模块的打开与关闭。",
--     ["Show"] = "显示",
--     ["ShowAll"] = "全部显示",
--     ["Toggles popups on and off for chat window %d."] = "切换窗口 %d 的弹出消息.",
--     ["Toggle showing Popup settings for each window."] = "切换每一窗口的弹出显示设置.",
--     ["Chat%dPopupShow"] = "显示窗口 %d 探出消息",
--     ["Toggles Popup on and off for all chat windows."] = "切换全部聊天窗口弹出消息.",
--     ["Choose mode for showing popups."] = "选择显示弹出消息方式.",
--     ["ShowMode"] = "显示模式",
--     ["All"] = "全部",
--     ["Individual"] = "个别",
--     ["An alternate name to show in popups."] = "显示弹出消息的替换名字.",
--     ["Add Nickname"] = "添加昵称",
--     ["Remove Nickname"] = "移除昵称",
--     ["Clear Nickname"] = "清除昵称",
-- } end)

L:RegisterTranslations("koKR", function() return {
    ["PopupMessage"] = "메세지팝업",
    ["Shows messages with your name in a popup."] = "당신의 이름을 포함한 메세지를 팝업으로 표시합니다.",
    ["Set Separately"] = "구분 설정",
    ["Toggle setting options separately for each chat window."] = "각각의 대화창에 구분 설정을 사용합니다.",
    ["Show Popups"] = "팝업 표시",
    ["Show Popups for each window."] = "각 대화창에 대한 팝업을 표시합니다.",
    ["Chat%dPopupShow"] = "대화창%d팝업표시",
    ["Show popups on and off for chat window %d."] = "대화창 %d에 대한 팝업을 표시합니다.",
    ["Show All Popups"] = "모든 팝업 표시",
    ["Show Popups for all chat windows."] = "모든 대화창에 대한 팝업을 표시합니다.",
    ["An alternate name to show in popups."] = "팝업으로 표시할 다른 이름입니다.",
    ["Add Nickname"] = "별명 추가",
    ["Remove Nickname"] = "별명 삭제",
    ["Clear Nickname"] = "별명 초기화",
    ["Use SCT Message"] = "SCT 메세지 사용",
    ["Show the text as an SCT message instead of in its own frame"] = "SCT 메세지로 팝업을 표시합니다.",
    ["Toggle"] = "사용",
    ["Toggle the module on and off."] = "기능 사용 여부를 결정합니다.",

    ["show_name"] = "표시",
    ["show_desc"] = "각각의 대화창에 시간을 표시합니다.",
    ["show_perframename"] = "대화창%d팝업표시",
    ["show_perframedesc"] = "대화창 %d에 대한 팝업을 표시합니다.",
    ["showall_name"] = "모든 팝업 표시",
    ["showall_desc"] = "모든 대화창에 대한 팝업을 표시합니다.",
    ["usesct_name"] = "SCT 메세지 사용",
    ["usesct_desc"] = "SCT 메세지로 팝업을 표시합니다.",
} end)

-- L:RegisterTranslations("zhTW", function() return {
--     ["PopupMessage"] = "彈出訊息",
--     ["Shows messages with your name in a popup."] = "在彈出視窗中顯示包含自己名字的訊息。",
--     ["Toggle"] = "切換",
--     ["Toggle the module on and off."] = "切換打開或關閉此模組。",
--     ["Show"] = "顯示",
--     ["ShowAll"] = "全部顯示",
--     ["Toggles popups on and off for chat window %d."] = "切換視窗 %d 的彈出訊息。",
--     ["Toggle showing Popup settings for each window."] = "切換每一視窗的彈出顯示設定。",
--     ["Chat%dPopupShow"] = "顯示視窗 %d 彈出訊息",
--     ["Toggles Popup on and off for all chat windows."] = "切換全部聊天視窗彈出訊息。",
--     ["Choose mode for showing popups."] = "選擇顯示彈出訊息方式。",
--     ["ShowMode"] = "顯示模式",
--     ["All"] = "全部",
--     ["Individual"] = "個別",
--     ["An alternate name to show in popups."] = "顯示彈出訊息的替換名字。",
--     ["Add Nickname"] = "加入暱稱",
--     ["Remove Nickname"] = "移除暱稱",
--     ["Clear Nickname"] = "清除暱稱",
-- } end)

L:RegisterTranslations("esES", function() return {
    ["PopupMessage"] = "Mensaje en Ventana Emergente",
    ["Shows messages with your name in a popup."] = "Muestras los mensajes con tu nombre en una ventana emergente",
    ["Set Separately"] = "Por Separado",
    ["Toggle setting options separately for each chat window."] = "Establece las opciones para cada ventana de chat por separado",
    ["Show Popups"] = "Mostrar ventanas emergentes",
    ["Show Popups for each window."] = "Muestra ventanas emergentes para cada ventana",
    ["Chat%dPopupShow"] = "Mostrar Ventana Emergente en Chat %d",
    ["Show popups on and off for chat window %d."] = "Muestra las ventanas emergentes para la ventana de chat %d",
    ["Show All Popups"] = "Mostrar Todas las Ventanas Emergentes",
    ["Show Popups for all chat windows."] = "Muestra las ventanas emergentes para todas las ventanas de chat",
    ["An alternate name to show in popups."] = "Un nombre alternativo para mostrar en las ventanas emergentes",
    ["Add Nickname"] = "A\195\177adir Pseud\195\179nimmo",
    ["Remove Nickname"] = "Eliminar Pseud\195\179nimo",
    ["Clear Nickname"] = "Borrar Pseud\195\179nimo",
 	["Use SCT Message"] = "Usar Mensaje SCT",
	["Show the text as an SCT message instead of in its own frame"] = "Muestra el texto como un mensaje de SCT en vez de en su propio marco",
    ["Toggle"] = "Activar",
    ["Toggle the module on and off."] = "Activa y desactiva este m\195\179dulo",

    ["show_name"] = "Mostrar",
    ["show_desc"] = "Muestra los ajustes de sello de tiempo para cada ventana.",
    ["show_perframename"] = "Mostrar Ventana Emergente en Chat %d",
    ["show_perframedesc"] = "Muestra las ventanas emergentes para la ventana de chat %d",
    ["showall_name"] = "Mostrar Todas las Ventanas Emergentes",
    ["showall_desc"] = "Muestra las ventanas emergentes para todas las ventanas de chat",
    ["usesct_name"] = "Usar Mensaje SCT",
    ["usesct_desc"] = "Muestra el texto como un mensaje de SCT en vez de en su propio marco",
} end)

L:RegisterTranslations("deDE", function() return {
	["PopupMessage"] = "Popup Nachrichten",
	["Shows messages with your name in a popup."] = "Zeige Nachrichten mit deinem Namen in einem Popup.",
	["Set Separately"] = "Seperat einstellen",
	["Toggle setting options separately for each chat window."] = "Aktiviert das seperate Einstellen der Optionen für jedes Chatfenster.",
	["Show Popups"] = "Zeige Popups",
	["Show Popups for each window."] = "Zeige Popups f\195\188r jedes Fenster.",
	["Chat%dPopupShow"] = "Chat %d Popup Anzeigen",
	["Show popups on and off for chat window %d."] = "Schaltet Popups an und aus f\195\188r Chatfenster %d.",
	["Show All Popups"] = "Zeige alle Popups",
	["Show Popups for all chat windows."] = "Zeige Popups f\195\188r alle Chatfenster.",
	["An alternate name to show in popups."] = "Einen alternativen Namen in den Popup's anzeigen.",
	["Add Nickname"] = "Nicknamen hinzuf\195\188gen",
	["Remove Nickname"] = "Entferne Nicknamen",
	["Clear Nickname"] = "L\195\182sche Nicknamen",
	["Use SCT Message"] = "Benutze SCT Nachrichtenfenster",
 	["Show the text as an SCT message instead of in its own frame"] = "Zeige die Texte als eine SCT Nachricht anstatt im eigenen Fenster.",
	["Toggle"] = "Einschalten",
	["Toggle the module on and off."] = "Schaltet das Modul an und aus.",

	["show_name"] = "Zeige",
	["show_desc"] = "Schaltet das Anzeigen des Zeitstempels f\195\188r jedes Fenster ein.",
	["show_perframename"] = "Chat %d Popup Anzeigen",
	["show_perframedesc"] = "Schaltet Popups an und aus f\195\188r Chatfenster %d.",
	["showall_name"] = "Zeige alle Popups",
	["showall_desc"] = "Zeige Popups f\195\188r alle Chatfenster.",
	["usesct_name"] = "Benutze SCT Nachrichtenfenster",
	["usesct_desc"] = "Zeige die Texte als eine SCT Nachricht anstatt im eigenen Fenster.",
} end)

local EVENTS_EMOTES = {
  ["CHAT_MSG_BG_SYSTEM_ALLIANCE"] = true,
  ["CHAT_MSG_BG_SYSTEM_HORDE"] = true,
  ["CHAT_MSG_BG_SYSTEM_NEUTRAL"] = true,
  ["CHAT_MSG_EMOTE"] = true,
  ["CHAT_MSG_TEXT_EMOTE"] = true,
  ["CHAT_MSG_MONSTER_EMOTE"] = true,
  ["CHAT_MSG_MONSTER_SAY"] = true,
  ["CHAT_MSG_MONSTER_WHISPER"] = true,
  ["CHAT_MSG_MONSTER_YELL"] = true,
  ["CHAT_MSG_RAID_BOSS_EMOTE"] = true
};

local EVENTS_IGNORE = {
 ["CHAT_MSG_CHANNEL_NOTICE_USER"] = true,
 ["CHAT_MSG_SYSTEM"] = true,
}

Prat_PopupMessage = Prat:NewModule(Prat:RequestModuleName("PratPopupMessage"))

Prat_PopupMessage.revision = tonumber(string.sub("$Revision: 27189 $", 12, -3))

-- Prat categories relevant to this module. list at: http://groups.google.com/group/wow-prat/web/prat-categories
local cat = Prat.Categories
Prat_PopupMessage.Categories	= { cat.INFO, cat.DEV, cat.FRAME, cat.BEHAVIOR }	-- eg { cat.TEXT, cat.INFO }

Prat_PopupMessage.defaultDB = {
    on = true,
    separate = true,
    show = {false, false, false, false, false, false, false},
    showall = false,
    secure = true,
    usesct = false,
    nickname = {},
}

Prat_PopupMessage.moduleOptions = {}
Prat_PopupMessage.toggleOptions = { show={}, usesct=125, }

-- Set this to true to use Prat Event Support
Prat_PopupMessage.supportsPratEvents = true

function Prat_PopupMessage:GetModuleOptions()
    self.moduleOptions = {
        name = L["PopupMessage"],
        desc = L["Shows messages with your name in a popup."],
        type = "group",
        args = {
            separate = {
                name = L["Set Separately"],
                desc = L["Toggle setting options separately for each chat window."],
                type = "toggle",
                order = 100,
                get = function() return self.db.profile.separate end,
                set = function(v) self.db.profile.separate = v end,
            },
            show = {
                name = L["Show Popups"],
                desc = L["Show Popups for each window."],
                type = "group",
                order = 110,
                args = {
                },
            },
            showall = {
                name = L["Show All Popups"],
                desc = L["Show Popups for all chat windows."],
                type = "toggle",
                order = 120,
                get = function() return self.db.profile.showall end,
                set = function(v)
                    self.db.profile.showall = v
                    for i=1,NUM_CHAT_WINDOWS do
                        self.db.profile.show[i] = v
                    end
                end,
                disabled = function() if self.db.profile.separate then return true else return false end end,
            },
            addnick = {
                name = L["Add Nickname"],
                desc = L["An alternate name to show in popups."],
                type = "text",
                order = 130,
                usage = "<string>",
                get = false,
				set = function(name) self:AddNickname(name) end
            },
            removenick = {
                name = L["Remove Nickname"],
                desc = L["An alternate name to show in popups."],
                type = "text",
                order = 130,
				current = "",
				get = function() return "" end,
				validate = self.db.profile.nickname,
                disabled = function() return #self.db.profile.nickname == 0 end,
				set = function(value) self:RemoveNickname(value) end
            },
            clearnick = {
                name = L["Clear Nickname"],
                desc = L["An alternate name to show in popups."],
				type = "execute",
                order = 130,
                disabled = function() return (#self.db.profile.nickname == 0) end,
				func = function() self:ClearNickname() end
            },
        },
    }


  	return self.moduleOptions
end

function Prat_PopupMessage:OnModuleEnable()
    self.moduleOptions.args.show.disabled = function() if not self.db.profile.separate then return true else return false end end
    self.moduleOptions.args.usesct.hidden = function() if SCT then return false else return true end end

	self:RegisterEvent("Prat_PostAddMessage")
    self.playerName = UnitName("player");
end

--[[------------------------------------------------
	Core Functions
------------------------------------------------]]--

function Prat_PopupMessage:Prat_PostAddMessage(message, frame, text, r, g, b, id)
	if not (EVENTS_EMOTES[event] or EVENTS_IGNORE[event]) then
		if self.db.profile.show[frame:GetID()] then
			if message.PLAYERLINK ~= self.playerName  or self:IsDebugging() then
				self:CheckText(message.MESSAGE, message.OUTPUT)
			end
		end
	end
end

function Prat_PopupMessage:AddNickname(name)
	for k, v in pairs(self.db.profile.nickname) do
		if v == name then
			return
		end
	end
	table.insert(self.db.profile.nickname, name)
end

function Prat_PopupMessage:RemoveNickname(name)
	for k, v in pairs(self.db.profile.nickname) do
		if v == name then
			table.remove(self.db.profile.nickname, k)
		end
	end
end

function Prat_PopupMessage:ClearNickname()
	while getn(self.db.profile.nickname) > 0 do
		table.remove(self.db.profile.nickname)
	end
end


local tmp_color = {}
local function safestr(s) return s or "" end
function Prat_PopupMessage:CheckText(text, display_text, r, g, b)
	local textL = string.lower(safestr(text))
	local playerL = string.lower(safestr(self.playerName))
    local shown = false
	for k, v in pairs(self.db.profile.nickname) do

		local nicknameL = v

		if (nicknameL ~= "" and not shown) then
			if string.find(textL, playerL) or string.find(textL, nicknameL) then
				--		    if string.find(textL, playerL) then
				if self.db.profile.usesct and SCT  then
					tmp_color.r, tmp_color.g, tmp_color.b = r, g, b 
         --           Prat:ConsoleDebugDump(tmp_color)
					SCT:DisplayMessage(display_text or text, tmp_color)
				else
					Prat_PopupFrame.fadeOut = 10;
					Prat_PopupFrame:SetAlpha(1);
					Prat_PopupFrameText:SetText(display_text or text);
					Prat_PopupFrame:Show();
				end
                shown = true;
				PlaySoundFile(Prat.sounds.popup);
			end
		end
	end
end

function Prat_PopupMessage:PopupUpdated(elapsed)
  Prat_PopupFrame.fadeOut = Prat_PopupFrame.fadeOut - elapsed;
  if Prat_PopupFrame.fadeOut < -1 then
    Prat_PopupFrame:Hide();
  elseif Prat_PopupFrame.fadeOut < 0 then
    Prat_PopupFrame:SetAlpha(1 + Prat_PopupFrame.fadeOut);
  end
end