---------------------------------------------------------------------------------
--
-- 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: PratChatButtons
Revision: $Revision: 28843 $
Author(s): Curney (asml8ed@gmail.com)
           Krtek (krtek4@gmail.com)
           Sylvanaar (sylvanaar@mindspring.com)
Inspired by: idChat2_Buttons by Industrial
Website: http://www.wowace.com/files/index.php?path=Prat/
Documentation: http://www.wowace.com/wiki/Prat/Integrated_Modules#Buttons
Subversion: http://svn.wowace.com/wowace/trunk/Prat/
Discussions: http://groups.google.com/group/wow-prat
Issues and feature requests: http://code.google.com/p/prat/issues/list
Description: Module for Prat that adds chat menu and button options.
Dependencies: Prat
]]

-- set prat module name
local PRAT_MODULE = Prat:RequestModuleName("PratChatButtons")

-- define localized strings
local L = AceLibrary("AceLocale-2.2"):new(PRAT_MODULE)

L:RegisterTranslations("enUS", function() return {
    ["ChatButtons"] = true,
    ["Chat menu and button options."] = true,
    ["chatmenu_name"] = "Show Chat Menu",
    ["chatmenu_desc"] = "Toggles chat menu on and off.",
    ["chatbutton_name"] = "Show Chat Buttons",
    ["chatbutton_desc"] = "Toggle chat buttons on and off for each chat window.",
    ["chatbutton_perframename"] = "Chat%dButtons",
    ["chatbutton_perframedesc"] = "Toggles buttons on and off for chat window %d.",
    ["position_name"] = "Set Position",
    ["position_desc"] = "Sets position of buttons for all chat windows.",
    ["Default"] = true,
    ["Right, Inside Frame"] = true,
    ["Right, Outside Frame"] = true,
    ["alpha_name"] = "Set Alpha",
    ["alpha_desc"] = "Sets alpha of buttons for all chat windows.",
    ["reminder_name"] = "Show ScrollDown Reminder",
    ["reminder_desc"] = "Show reminder button when not at the bottom of a chat window.",
} end)

L:RegisterTranslations("deDE", function() return {
    ["ChatButtons"] = "Chat Tasten",
    ["Chat menu and button options."] = "Chat Fenster Men\195\188 und Tasten Optionen.",
    ["chatmenu_name"] = "Zeige Chat Menu",
    ["chatmenu_desc"] = "Schaltet das Chat Men\195\188 ein und aus.",
    ["chatbutton_name"] = "Zeige Chat Tasten",
    ["chatbutton_desc"] = "Schaltet die Chat Tastens ein und aus für jedes Chatfenster.",
    ["chatbutton_perframename"] = "Chat %d Tasten",
    ["chatbutton_perframedesc"] = "Schaltet die Buttons ein und aus f\195\188r das Chatfenster %d.",
    ["position_name"] = "Position festlegen",
    ["position_desc"] = "Position der Tasten festlegen f\195\188r alle Chatfenster.",
    ["Default"] = "Grundeinstellung",
    ["Right, Inside Frame"] = "Rechts, im Fensters",
    ["Right, Outside Frame"] = "Rechts, am Fenster",
    ["alpha_name"] = "Helligkeit festlegen",
    ["alpha_desc"] = "Helligkeit der Tasten festlegen f\195\188r alle Chatfenster.",
    ["reminder_name"] = "Zeige Erinnerungs Button",
    ["reminder_desc"] = "Zeige den Erinnerungs Button wenn man nicht am Ende des Chattextes ist.",
} end)

L:RegisterTranslations("frFR", function() return {
    ["ChatButtons"] = "Boutons de discussion",
    ["Chat menu and button options."] = "Options du menu et des boutons de chat.",
    ["chatmenu_name"] = "Afficher le menu de chat",
    ["chatmenu_desc"] = "Affiche ou masque le menu de chat.",
    ["chatbutton_name"] = "Afficher les boutons de chat",
    ["chatbutton_desc"] = "Affiche ou masque les boutons pour chaque fen\195\170tre de chat.",
    ["chatbutton_perframename"] = "Boutons du chat %d",
    ["chatbutton_perframedesc"] = "Affiche ou masque les boutons pour la fen\195\170tre de chat %d.",
    ["position_name"] = "Position des boutons",
    ["position_desc"] = "Change la position des boutons pour chaque fen\195\170tre de chat.",
    ["Default"] = "D\195\169faut",
    ["Right, Inside Frame"] = "Droite, à l'int\195\169rieur",
    ["Right, Outside Frame"] = "Droite, a l'ext\195\169rieur",
    ["alpha_name"] = "R\195\169gler la transparence",
    ["alpha_desc"] = "R\195\168gle la transparence de tous les boutons.",
    ["reminder_name"] = "Afficher le bouton de rappel de d\195\169filement",
    ["reminder_desc"] = "Affiche un bouton pour retourner en bas de la fen\195\170tre de chat quand vous n'y \195\170tes pas.",
} end)

L:RegisterTranslations("esES", function() return {
    ["ChatButtons"] = "Botones",
    ["Chat menu and button options."] = "Opciones del men\195\186 de chat y botones",
    ["chatmenu_name"] = "Men\195\186 de Chat",
    ["chatmenu_desc"] = "Activa y desactiva el men\195\186 de chat",
    ["chatbutton_name"] = "Botones de Chat",
    ["chatbutton_desc"] = "Activa y desactiva los botones de las ventanas de chat",
    ["chatbutton_perframename"] = "Botones del Chat %d",
    ["chatbutton_perframedesc"] = "Activa y desactiva los botones de la ventana de chat %d",
    ["position_name"] = "Posici\195\179n",
    ["position_desc"] = "Posici\195\179n de los botones para todas las ventanas de chat.",
    ["Default"] = "Por Defecto",
    ["Right, Inside Frame"] = "Derecha, dentro del marco",
    ["Right, Outside Frame"] = "Derecha, fuera del marco",
    ["alpha_name"] = "Transparencia",
    ["alpha_desc"] = "Transparencia de los botones para todas las ventanas de chat.",
    ["reminder_name"] = "Mostrar Bot\195\179n de Recordatorio",
    ["reminder_desc"] = "Muestra el bot\195\179n de recordatorio cuando no est\195\161s en la parte inferior de una ventana de chat.",
} end)

L:RegisterTranslations("koKR", function() return {
    ["ChatButtons"] = "대화버튼",
    ["Chat menu and button options."] = "대화창 메뉴와 버튼을 설정합니다.",
    ["chatmenu_name"] = "대화 메뉴 표시",
    ["chatmenu_desc"] = "대화 메뉴를 표시합니다.",
    ["chatbutton_name"] = "대화 버튼 표시",
    ["chatbutton_desc"] = "각각의 대화창에 대화 버튼을 표시합니다.",
    ["chatbutton_perframename"] = "대화창%d버튼",
    ["chatbutton_perframedesc"] =  "대화창 %d에 대한 버튼을 표시합니다.",
    ["position_name"] = "위치 설정",
    ["position_desc"] = "모든 대화창에 대한 버튼의 위치를 설정합니다.",
    ["Default"] = "기본",
    ["Right, Inside Frame"] = "우측, 창 내부",
    ["Right, Outside Frame"] = "우측, 창 외부",
    ["alpha_name"] = "투명도 설정",
    ["alpha_desc"] = "모든 대화창에 대한 버튼의 투명도를 설정합니다.",
    ["reminder_name"] = "스크롤 버튼 표시",
    ["reminder_desc"] = "대화창의 하단이 아니면 스크롤 버튼을 표시합니다.",
} end)

-- L:RegisterTranslations("zhCN", function() return {
--     ["ChatButtons"] = "按钮",
--     ["Chat menu and button options."] = "聊天窗口菜单及按钮选项。",
--     ["chatmenu_name"] = "聊天菜单",
--     ["chatmenu_desc"] = "显示聊天菜单打开与关闭。",
--     ["chatbutton_name"] = "聊天按钮",
--     ["chatbutton_desc"] = "切换显示聊天按钮打开与关闭。",
--     ["chatbutton_perframename"] = "聊天%d按钮",
--     ["chatbutton_perframedesc"] = "显示第 %d 聊天窗口按钮。",
--     ["position_name"] = "Set Position",
--     ["position_desc"] = "Sets position of buttons for all chat windows.",
--     ["Default"] = true,
--     ["Right, Inside Frame"] = true,
--     ["Right, Outside Frame"] = true,
--     ["alpha_name"] = "Set Alpha",
--     ["alpha_desc"] = "Sets alpha of buttons for all chat windows.",
--     ["reminder_name"] = "显示提示按钮",
--     ["reminder_desc"] = "聊天窗口不在底部时显示提示按钮。",
-- } end)

-- L:RegisterTranslations("zhTW", function() return {
--     ["ChatButtons"] = "按鈕",
--     ["Chat menu and button options."] = "聊天視窗選單及按鈕選項。",
--     ["chatmenu_name"] = "聊天選單",
--     ["chatmenu_desc"] = "顯示聊天選單打開與關閉。",
--     ["chatbutton_name"] = "聊天按鈕",
--     ["chatbutton_desc"] = "切換顯示聊天按鈕打開與關閉。",
--     ["chatbutton_perframename"] = "聊天%d按鈕",
--     ["chatbutton_perframedesc"] = "顯示第 %d 聊天視窗按鈕。",
--     ["position_name"] = "Set Position",
--     ["position_desc"] = "Sets position of buttons for all chat windows.",
--     ["Default"] = true,
--     ["Right, Inside Frame"] = true,
--     ["Right, Outside Frame"] = true,
--     ["alpha_name"] = "Set Alpha",
--     ["alpha_desc"] = "Sets alpha of buttons for all chat windows.",
--     ["reminder_name"] = "顯示提示按鈕",
--     ["reminder_desc"] = "聊天視窗不在底部時顯示提示按鈕。",
-- } end)

-- get prat module categories
local cat = Prat.Categories

-- create prat module
Prat_ChatButtons = Prat:NewModule(PRAT_MODULE)
Prat_ChatButtons.revision = tonumber(string.sub("$Revision: 28843 $", 12, -3))

-- define key module values
Prat_ChatButtons.moduleName = L["ChatButtons"]
Prat_ChatButtons.moduleDesc = L["Chat menu and button options."]
Prat_ChatButtons.consoleName = "chatbuttons"
Prat_ChatButtons.guiName = L["ChatButtons"]
Prat_ChatButtons.Categories = { cat.BUTTON, cat.FRAME }

-- define the default db values
Prat_ChatButtons.defaultDB = {
    on = true,
    chatmenu = false,
    chatbutton = {false, false, false, false, false, false, false},
    reminder = false,
    position = "DEFAULT",
    alpha = 1.0,
}

-- build the options menu using prat templates
Prat_ChatButtons.toggleOptions = {
    chatmenu = { type="toggle", order = 150, set = function(v) Prat_ChatButtons.db.profile.chatmenu = v Prat_ChatButtons:ChatMenu(v) end },
    chatbutton_handler = {},
    reminder = 170,
    optsep_sep = 175,
    position_options = {["DEFAULT"] = L["Default"], ["RIGHTINSIDE"] = L["Right, Inside Frame"], ["RIGHTOUTSIDE"] = L["Right, Outside Frame"]},
    alpha = {type="range", min=0.1, max=1, step=.1, order=190}
}
-- create a moduleOptions stub (for setting self.moduleOptions)
Prat_ChatButtons.moduleOptions = {}

--[[------------------------------------------------
    Module Event Functions
------------------------------------------------]]--

-- things to do when the module is enabled
function Prat_ChatButtons:OnModuleEnable()
    -- fix menu ordering
    self.moduleOptions.args.chatbutton.order = 160
    self.moduleOptions.args.position.order = 180
    -- stub variables for frame handling
    self.frames = {}
    self.frames.cfScrl = {}
    self.reminders = {}
    -- create reminder buttons
    for i = 1,NUM_CHAT_WINDOWS do
        table.insert(self.reminders, self:MakeReminder(i))
        self:chatbutton(i,self.db.profile.chatbutton[i])
    end
    self:ChatMenu(self.db.profile.chatmenu)
    -- wat da hook gon be?
    self:SecureHook("ChatFrame_OnUpdate")
end

-- things to do when the module is disabled
function Prat_ChatButtons:OnModuleDisable()
    -- show chatmenu
    self:ChatMenu(true)
    -- show all the chatbuttons
    for i = 1,NUM_CHAT_WINDOWS do
        self:chatbutton(i,true)
    end
    -- unhook functions
    self:UnhookAll()
end

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

function Prat_ChatButtons:ConfigureAllFrames()
    for i = 1,NUM_CHAT_WINDOWS do
        self:chatbutton(i,self.db.profile.chatbutton[i])
    end
    self:ChatMenu(self.db.profile.chatmenu)
end

-- do something with the hook
function Prat_ChatButtons:ChatFrame_OnUpdate(elapsedSec)
    if ( not this:IsVisible() ) then
        return;
    end
    local id = this:GetID()
    local show = self.db.profile.chatbutton[id]
    
    self:chatbutton(id, show)
    self:ChatFrame_OnUpdateTextFlow(elapsed)


    -- This is all code for the 'reminder' from here on
    if show then
        return
    end
    if not self.db.profile.reminder then
        return
    end
    local remind = getglobal(this:GetName().."ScrollDownReminder");
    local flash = getglobal(this:GetName().."ScrollDownReminderFlash");
    if ( not flash ) then
        return
    end
    if ( this:AtBottom() ) then
        if ( remind:IsVisible() ) then
            remind:Hide();
            UIFrameFlashRemoveFrame(flash)
        end
        return;
    else
        if ( remind:IsVisible() ) then
            return
        end
        remind:Show()
        UIFrameFlash(flash, 0, 0, -1, false, CHAT_BUTTON_FLASH_TIME, CHAT_BUTTON_FLASH_TIME)
    end
end


-- manipulate chatframe menu button
function Prat_ChatButtons:ChatMenu(visible)
    -- define variables used
    local f = self.frames
    f.cfScrl.up = getglobal("ChatFrame1UpButton")
    -- chatmenu position:
    -- position chatmenu under the UpButton for chatframe1 if button position is set to "RIGHTINSIDE"
    -- otherwise position chatmenu above the UpButton for chatframe1
    ChatFrameMenuButton:ClearAllPoints()
    if self.db.profile.position == "RIGHTINSIDE" then
        ChatFrameMenuButton:SetPoint("TOP", f.cfScrl.up, "BOTTOM")
    else
        ChatFrameMenuButton:SetPoint("BOTTOM", f.cfScrl.up, "TOP")
    end
    -- chatmenu alpha:
    -- set alpha of the chatmenu based on the alpha setting
    ChatFrameMenuButton:SetAlpha(self.db.profile.alpha)
    -- chatmenu visibility
    -- show buttons based on show settings
    if visible then
        ChatFrameMenuButton:Show()
    else
        ChatFrameMenuButton:Hide()
    end
end

-- manipulate chatframe scrolling and reminder buttons
function Prat_ChatButtons:chatbutton(id,visible)
    -- define variables used
    local f = self.frames
    f.cf = getglobal("ChatFrame"..id)
    f.cfScrl.up = getglobal("ChatFrame"..id.."UpButton")
    f.cfScrl.down = getglobal("ChatFrame"..id.."DownButton")
    f.cfScrl.bottom = getglobal("ChatFrame"..id.."BottomButton")
    f.cfreminder = getglobal("ChatFrame"..id.."ScrollDownReminder")
    f.cfreminderflash = getglobal("ChatFrame"..id.."ScrollDownReminderFlash")
    -- chatbuttons position:
    -- position of the chatbuttons based on position setting
    f.cfScrl.bottom:ClearAllPoints()
    f.cfScrl.up:ClearAllPoints()
    if self.db.profile.position == "RIGHTINSIDE" then
        f.cfScrl.bottom:SetPoint("BOTTOMRIGHT", f.cf, "BOTTOMRIGHT", 0, -4)
        f.cfScrl.up:SetPoint("TOPRIGHT", f.cf, "TOPRIGHT", 0, -4)
    elseif self.db.profile.position == "RIGHTOUTSIDE" then
        f.cfScrl.bottom:SetPoint("BOTTOMLEFT", f.cf, "BOTTOMRIGHT", 0, -4)
        f.cfScrl.up:SetPoint("BOTTOM", f.cfScrl.down, "TOP", 0, -2)
    else
        f.cfScrl.bottom:SetPoint("BOTTOMLEFT", f.cf, "BOTTOMLEFT", -32, -4)
        f.cfScrl.up:SetPoint("BOTTOM", f.cfScrl.down, "TOP", 0, -2)
    end
    -- chatbuttons alpha:
    -- set alpha of the chatbuttons based on the alpha setting
    for _,v in pairs(f.cfScrl) do
        v:SetAlpha(self.db.profile.alpha)
    end
    -- chatbuttons visibility:
    -- show buttons based on visible value passed to function
    if visible then
        for k, v in pairs(f.cfScrl) do
            f.cfScrl[k]:Show()
        end
    else
        for k, v in pairs(f.cfScrl) do
            f.cfScrl[k]:Hide()
        end
        -- reminder visibility:
        -- show the reminder button (if enabled) when not at the bottom of the chatframe
        if (not f.cf:AtBottom()) and self.db.profile.reminder then
            f.cfreminder:Show()
            f.cfreminderflash:Show()
        else
            f.cfreminder:Hide()
            f.cfreminderflash:Hide()
        end
    end
end

-- create a "reminder" button
function Prat_ChatButtons:MakeReminder(id)
    -- define variables used
    local cf = getglobal("ChatFrame"..id)
    local b = getglobal("ChatFrame"..id.."ScrollDownReminder")
    if b then return b end
    b = CreateFrame("Button","ChatFrame"..id.."ScrollDownReminder",cf )
    -- define the parameters for the button
    b:SetFrameStrata("BACKGROUND")
    b:SetWidth(24)
    b:SetHeight(24)
    b:SetNormalTexture("Interface\\ChatFrame\\UI-ChatIcon-ScrollEnd-Up")
    b:SetPushedTexture("Interface\\ChatFrame\\UI-ChatIcon-ScrollEnd-Down")
    b:SetHighlightTexture("Interface\\Buttons\\UI-Common-MouseHilight")
    b:SetPoint("RIGHT", cf, "RIGHT", 0, 0)
    b:SetPoint("LEFT", cf, "RIGHT", -32, 0)
    b:SetPoint("TOP", cf, "BOTTOM", 0, 28)
    b:SetPoint("BOTTOM", cf, "BOTTOM", 0, 0)
    b:SetScript("OnClick", function() PlaySound("igChatBottom"); this:GetParent():ScrollToBottom() end)
    -- hide the button by default
    b:Hide()
    -- add a flash texture for the reminder button
    self:AddFlashTexture(b)

    return b
end

-- create a "flash" texture
function Prat_ChatButtons:AddFlashTexture(frame)
    -- define variables used
    local t = frame:CreateTexture(frame:GetName().."Flash", "OVERLAY")
    -- define the parameters for the texture
    t:SetTexture("Interface\\ChatFrame\\UI-ChatIcon-BlinkHilight")
    t:SetPoint("CENTER", frame, "CENTER", 0, 1)
    t:SetBlendMode("ADD")
    t:SetAlpha(0.5)
    -- hide the texture by default
    t:Hide()
end

--[[------------------------------------------------
    Unused Functions
------------------------------------------------]]--

-- These are some fancy-ish enhacements we can enable
--
-- 1) Alpha to full on mouseover
-- 2) Glowy border on mouseover
-- 3) Automatically adjust right margin so text doesnt overlap the buttons

-- OnEnter/Exit Handlers for glowy border buttons
function Prat_ChatButtons:GlowBtnOnEnter()
    local flash = getglobal(this:GetName().."Flash");
    flash:Show()
    this:SetAlpha(1.0)
end

function Prat_ChatButtons:GlowBtnOnLeave()
    local flash = getglobal(this:GetName().."Flash");
    flash:Hide()
    this:SetAlpha(self.db.profile.alpha)
end

-- OnEnter/Exit Handlers for alpha hide/unhide buttons
function Prat_ChatButtons:AlphaHideBtnOnEnter()
    this:SetAlpha(1.0)
end

function Prat_ChatButtons:AlphaHideBtnOnLeave()
    this:SetAlpha(self.db.profile.alpha)
end

local avoid_frames = {}

function intersects_pts(o1t, o1b,  o2t, o2b)
    -- above
    local above = o1t > o2t and o1b > o2t

    -- below
    local below = o1t < o2b and o1b < o2b

    -- either one true and we dont intersect
    return not( above or below )
end


function intersects_line(line, frame)
    return intersects_pts(line:GetTop(), line:GetBottom(), frame:GetTop(), frame:GetBottom())
end


-- Sample code to show how to flow text around a button which is on the frame
function Prat_ChatButtons:ChatFrame_OnUpdateTextFlow(elapsed)
    if self.db.profile.position == "RIGHTINSIDE" then
        avoid_frames.cfup = getglobal("ChatFrame"..this:GetID().."UpButton")
        avoid_frames.cfdown = getglobal("ChatFrame"..this:GetID().."DownButton")
        avoid_frames.cfbottom = getglobal("ChatFrame"..this:GetID().."BottomButton")
        avoid_frames.cfreminder = getglobal("ChatFrame"..this:GetID().."ScrollDownReminder")

        for i=this:GetNumRegions(),1,-1 do
            local line = select(i, this:GetRegions())
            if line:GetObjectType() == "FontString" then
                local found = false
                for k,v in pairs(avoid_frames) do
                    if v:IsVisible() and intersects_line(line, v) then
                        line:SetPoint("RIGHT", v, "LEFT", 0, 0)
                        _,_,w,_ =line:GetRect()
                        line:SetWidth(w)
                        found = true
                        break
                    end
                end

                if not found then 
                    line:SetPoint("RIGHT", this, "RIGHT", 0, 0)
                    _,_,w,_ =line:GetRect()
                    line:SetWidth(w)
                end                                
                
            end
        end
    end
end