---------------------------------------------------------------------------------
--
-- 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: PratFont
Revision: $Revision: 46600 $
Author(s): Curney (asml8ed@gmail.com)
Inspired by: ChatFrameExtender by Satrina
Website: http://www.wowace.com/files/index.php?path=Prat/
Documentation: http://www.wowace.com/wiki/Prat/Integrated_Modules#Font
SVN: http://svn.wowace.com/wowace/trunk/Prat/
Description: Module for Prat that allows you to set the font face and size for chat windows (default=blizz default font face at size 12).
Dependencies: Prat
]]

-- Get Utility Libraries
local util, DBG, CLR = GetPratUtils()

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

if PRAT_MODULE == nil then 
    return 
end

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

L:RegisterTranslations("enUS", function() return {
    ["Font"] = true,
    ["Chat window font options."] = true,
    ["Set Separately"] = true,
    ["Toggle setting options separately for each chat window."] = true,
    ["Set Font Face"] = true,
    ["Set the text font face for all chat windows."] = true,
    ["rememberfont_name"] = "Remember Font",
    ["rememberfont_desc"] = "Remember your font choice and restore it at startup.",    
    ["Set Font Size"] = true,
    ["Set text font size for each chat window."] = true,
    ["Set ChatFrame%d Font Size"] = true,
    ["Set text font size."] = true,
    ["Automatic Restore"] = true,
    ["Workaround a Blizzard bug which changes the font size when you open a system menu."] = true,
    ["textenh_name"] = "Text Effects",
    ["textenh_desc"] = "Other effects to the chat text appearance.",
    ["outlinefont_name"] = "Toggle Shadow",
    ["outlinefont_desc"] = "Show shadow effect on current font.",    
    ["outlinecolor_name"] = "Set Shadow Color",
    ["outlinecolor_desc"] = "Set the color of the shadow effect.",    
} end)

--[[
	Chinese Local : CWDG Translation Team 昏睡墨鱼 (Thomas Mo)
	CWDG site: http://Cwowaddon.com
	$Rev: 46600 $
	$Date: 2007-08-15 04:17:04 +0200 (Wed, 15 Aug 2007) $
]]

L:RegisterTranslations("zhCN", function() return {
	["Font"] = "字体尺寸",
	["Chat window font options."] = "聊天窗口字体尺寸选项.",
    ["Set Separately"] = "独立设置",
    ["Toggle setting options separately for each chat window."] = "独立切换每个聊天窗口选项.",
    ["Set Font Face"] = "字体",
    ["Set the text font face for all chat windows."] = "设置聊天文本字体",
    ["rememberfont_name"] = "记录字体",
    ["rememberfont_desc"] = "记录字体选择并在启动时恢复.",
    ["Set Font Size"] = "字体大小",
    ["Set text font size for each chat window."] = "每个聊天窗口的字体大小.",
    ["Set ChatFrame%d Font Size"] = "聊天窗口 %d 字体大小",
    ["Set text font size."] = "设置聊天窗口 %d 字体大小.",
    ["Automatic Restore"] = "自动恢复",
    ["Workaround a Blizzard bug which changes the font size when you open a system menu."] = "解决打开系统菜单后字体大小变化的错误.",
    ["textenh_name"] = "最强文本",
    ["textenh_desc"] = "其他聊天文本外观增强.",
} end)

L:RegisterTranslations("zhTW", function() return {
    ["Font"] = "字體大小",
    ["Chat window font options."] = "聊天視窗字體大小選項",
    ["Set Font Face"] = "設定字體大小",
    ["Set the text font face for all chat windows."] = "設定各視窗字體大小",
    ["Set Font Size"] = "設定字體大小",
    ["Set text font size for each chat window."] = "設定各視窗字體大小",
    ["Set ChatFrame%d Font Size"] = "聊天視窗 %d 字體大小",
    ["Set text font size."] = "設定 %d 視窗字體大小",
    ["autorestore_name"] = "自動記憶設定",
    ["Workaround a Blizzard bug which changes the font size when you open a system menu."] = "修正 Blizzard 的錯誤：當你開啟系統選單時會改變字體大小",
    ["textenh_name"] = "文字增強",
    ["textenh_desc"] = "其他對聊天文字外觀的改進",
} end)

L:RegisterTranslations("frFR", function() return {
    ["Font"] = "Taille du texte",
    ["Chat window font options."] = "Options des tailles des textes",
    ["Set Font Size"] = "Changer la taille des textes",
    ["Set text font size for each chat window."] = "Change la taille du texte pour chaque fen\195\170tre.",
    ["Set ChatFrame%d Font Size"] = "Taille du texte, fen\195\170tre %d",
    ["Set text font size."] = "Change la taille du texte pour la fen\195\170tre %d.",
    ["textenh_name"] = "Am\195\169liorations du texte",
    ["textenh_desc"] = "Autres am\195\169liorations de l'apparence du texte.",
} end)

L:RegisterTranslations("koKR", function() return {
    ["Font"] = "글꼴",
    ["Chat window font options."] = "대화창 글꼴을 설정합니다.",
    ["Set Separately"] = "구분 설정",
    ["Toggle setting options separately for each chat window."] = "각각의 대화창에 대한 글꼴을 설정합니다.",
    ["Set Font Face"] = "글꼴 설정",
    ["Set the text font face for all chat windows."] = "모든 대화창의 글꼴을 설정합니다.",
    ["rememberfont_name"] = "글꼴 기억",
    ["rememberfont_desc"] = "설정된 사항을 기억하고 시작시에 적용합니다.",    
    ["Set Font Size"] = "글꼴 크기 설정",
    ["Set text font size for each chat window."] = "각각의 대화창의 글꼴 크기를 설정합니다.",
    ["Set ChatFrame%d Font Size"] = "%d번 대화창의 글꼴 크기를 설정합니다.",
    ["Set text font size."] = "글꼴 크기 설정",
    ["Automatic Restore"] = "자동 적용",
    ["Workaround a Blizzard bug which changes the font size when you open a system menu."] = "기본 메뉴를 열 때 폰트 크기가 변경되는 블리자드 오류를 수정합니다",
    ["textenh_name"] = "글꼴 효과",
    ["textenh_desc"] = "대화글에 기타 효과를 추가합니다.",
    ["outlinefont_name"] = "음영 사용",
    ["outlinefont_desc"] = "현재 글꼴에 음영 효과를 추가합니다.",    
    ["outlinecolor_name"] = "음영 색상 설정",
    ["outlinecolor_desc"] = "음영 효과의 색상을 설정합니다.",    
} end)

L:RegisterTranslations("esES", function() return {
    ["Font"] = "Tama\195\177o de Fuente",
    ["Chat window font options."] = "Opciones del tama\195\177o de fuente en las ventanas de chat",
    ["Set Font Size"] = "Tama\195\177o de Fuente",
    ["Set text font size for each chat window."] = "Establece el tama\195\177o de fuente para cada ventana de chat",
    ["Set ChatFrame%d Font Size"] = "Tama\195\177o de Fuente del Chat %d",
    ["Set text font size."] = "Establece el tama\195\177o de fuente para la ventana de chat %d",
    ["autorestore_name"] = "Recuperaci\195\179n Autom\195\161tica",
    ["Workaround a Blizzard bug which changes the font size when you open a system menu."] = "Solucina temporalmente un bug de Blizzard que cambia el tama\195\177o de fuente cuando abres el men\195\186 de sistema.",
    ["textenh_name"] = "Mejoras de Texto",
    ["textenh_desc"] = "Otras mejoras a la apariencia del texto de chat",
} end)

L:RegisterTranslations("deDE", function() return {
	["Font"] = "Schriftgr\195\182\195\159e",
	["Chat window font options."] = "Chatfenster Schriftgr\195\182\195\159en Optionen.",
	["Set Font Size"] = "Setze Schriftgr\195\182\195\159e",
	["Set text font size for each chat window."] = "Setze Schriftgr\195\182\195\159e f\195\188r jedes Fenster.",
	["Set ChatFrame%d Font Size"] = "Chat %d Schriftgr\195\182\195\159e",
	["Set text font size."] = "Setze Schrifgr\195\182\195\159e f\195\188r Chatfenster %d.",
	["textenh_name"] = "Text Verbesserungen",
	["textenh_desc"] = "Weitere Verbeserrungen f\195\188r das Chattext Erscheinungsbild.",
} end)

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

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

-- define key module values
Prat_Font.moduleName = L["Font"] 	
Prat_Font.moduleDesc = L["Chat window font options."]
Prat_Font.consoleName = string.lower(Prat_Font.moduleName)
Prat_Font.guiName = L["Font"]
Prat_Font.Categories = { cat.TEXT, cat.FORMATTING }

-- define the default db values
Prat_Font.defaultDB = {
    on = true,
    size = {12, 12, 12, 12, 12, 12, 12},
    autorestore = false, 
    font = "",
    rememberfont = false,
    outlinefont = false,
    outlinecolor = {
        r = 0,
        g = 0,
        b = 0,
        a = 1,
    },
--    sizeseparate = true,
--    sizeall = 12,
}

-- Fix the defaults that are being used for the chatframe text font size.
for i=1,NUM_CHAT_WINDOWS do
    local cf = getglobal("ChatFrame"..i)
    local _, s, _ = cf:GetFont()    
    Prat_Font.defaultDB.size[i]  = s
end

-- create a moduleOptions stub (for setting self.moduleOptions)
Prat_Font.moduleOptions = {}

-- build the options menu using prat templates
Prat_Font.toggleOptions = { 
    sep125_sep = 125,
    rememberfont = 140,
    sep145_sep = 145,
    outlinefont = { 
        type = "toggle",
        order = 150,
        get = function() return Prat_Font.db.profile.outlinefont end,
        set = function(v) Prat_Font.db.profile.outlinefont = v; Prat_Font:ConfigureAllChatFrames() end
    },
    outlinecolor = { type = "color", order = 160, get = "GetShadowClr", set = "SetShadowClr" } 
}

local fontslist = {}
local media 

function Prat_Font:BuildFontList()
    for i,v in ipairs(fontslist) do
        fontslist[i] = nil
    end
    
    for k,v in pairs(media:List(media.MediaType.FONT)) do
        table.insert(fontslist, v)
    end
end

function Prat_Font:SharedMedia_Registered(mediatype, name)
    if mediatype == media.MediaType.FONT then
        self:BuildFontList()
    end
end

function Prat_Font:GetModuleOptions()
    self.moduleOptions = {
        name = L["Font"],
        desc = L["Chat window font options."],
        type = "group",
        args = {
            fontsize = {
                name = L["Set Font Size"],
                desc = L["Set text font size for each chat window."],
                type = "group",
                order = 110,
                args = {
                    chat1 = {
                        name = string.format(L["Set ChatFrame%d Font Size"], 1),
                        desc = string.format(L["Set text font size."], 1),
                        type = "range",
                        get = function() return self.db.profile.size[1] end,
                        set = function(v) self.db.profile.size[1] = v; self:SetSize(1,v) end,
                        min = 4,
                        max = 22,
                        step = 1
                    },
                    chat2 = {
                        name = string.format(L["Set ChatFrame%d Font Size"], 2),
                        desc = string.format(L["Set text font size."], 2),
                        type = "range",
                        get = function() return self.db.profile.size[2] end,
                        set = function(v) self.db.profile.size[2] = v; self:SetSize(2,v) end,
                        min = 4,
                        max = 22,
                        step = 1
                    },
                    chat3 = {
                        name = string.format(L["Set ChatFrame%d Font Size"], 3),
                        desc = string.format(L["Set text font size."], 3),
                        type = "range",
                        get = function() return self.db.profile.size[3] end,
                        set = function(v) self.db.profile.size[3] = v; self:SetSize(3,v) end,
                        min = 4,
                        max = 22,
                        step = 1
                    },
                    chat4 = {
                        name = string.format(L["Set ChatFrame%d Font Size"], 4),
                        desc = string.format(L["Set text font size."], 4),
                        type = "range",
                        get = function() return self.db.profile.size[4] end,
                        set = function(v) self.db.profile.size[4] = v; self:SetSize(4,v) end,
                        min = 4,
                        max = 22,
                        step = 1
                    },
                    chat5 = {
                        name = string.format(L["Set ChatFrame%d Font Size"], 5),
                        desc = string.format(L["Set text font size."], 5),
                        type = "range",
                        get = function() return self.db.profile.size[5] end,
                        set = function(v) self.db.profile.size[5] = v; self:SetSize(5,v) end,
                        min = 4,
                        max = 22,
                        step = 1
                    },
                    chat6 = {
                        name = string.format(L["Set ChatFrame%d Font Size"], 6),
                        desc = string.format(L["Set text font size."], 6),
                        type = "range",
                        get = function() return self.db.profile.size[6] end,
                        set = function(v) self.db.profile.size[6] = v; self:SetSize(6,v) end,
                        min = 4,
                        max = 22,
                        step = 1
                    },
                    chat7 = {
                        name = string.format(L["Set ChatFrame%d Font Size"], 7),
                        desc = string.format(L["Set text font size."], 7),
                        type = "range",
                        get = function() return self.db.profile.size[7] end,
                        set = function(v) self.db.profile.size[7] = v; self:SetSize(7,v) end,
                        min = 4,
                        max = 22,
                        step = 1
                    },
                }
            },
            autorestore = { 
                name = L["Automatic Restore"],
                desc = L["Workaround a Blizzard bug which changes the font size when you open a system menu."],
                type = "toggle",
                order = 120,
                get = function() return self.db.profile.autorestore end,
                set = function(v) self.db.profile.autorestore = v; self:SetAutoRestore(v) end
            },
            fontface = {
                name = L["Set Font Face"],
                desc = L["Set the text font face for all chat windows."],
                type = "text",
                order = 130,
                get = function() return self.db.profile.font end,
                set = function(v) self.db.profile.font = v; self:SetFont(v) end,
                validate = fontslist,
            }
        }
    }
    return self.moduleOptions
end

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

function Prat_Font:OnModuleEnable()
    -- fix menu ordering
    self.moduleOptions.args.rememberfont.order = 140

    media = media or AceLibrary("SharedMedia-1.0")
    self.oldsize = {}
    self:BuildFontList()
	self:RegisterEvent("SharedMedia_Registered")
    
    for i=1,NUM_CHAT_WINDOWS do
        local cf = getglobal("ChatFrame"..i)
        local _, s, _ = cf:GetFont()    
        self.oldsize[i]  = s
    end
    
    if self.db.profile.rememberfont and self.db.profile.font then
        self:SetFont(self.db.profile.font)
    end
    
    self:ConfigureAllChatFrames()
    -- This will resolve the issue where, when font sizes are set smaller than 12,
    -- the size resets to 12 when closing UIOptionsFrame.
    self:SetAutoRestore(self.db.profile.autorestore)
    
    self:SecureHook("FCF_SetChatWindowFontSize")
end

function Prat_Font:OnModuleDisable()
    for i=1,NUM_CHAT_WINDOWS do
        self:SetSize(i,self.oldsize[i] or 12)
    end
end

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

function Prat_Font:ConfigureAllChatFrames()
    for i = 1,NUM_CHAT_WINDOWS do
        self:SetSize(i, self.db.profile.size[i])
    end
    if not self.db.profile.outlinefont then 
        self:SetFontMode("OUTLINE")
    else
        self:SetFontMode("")
    end        
end

function Prat_Font:SetSize(id, size)
--    local font = getglobal("ChatFrame"..id):GetFont()
--    getglobal("ChatFrame"..id):SetFont(font,size)

    FCF_SetChatWindowFontSize(getglobal("ChatFrame"..id), size)
end

function Prat_Font:SetFont(font)
    fontfile = media:Fetch(media.MediaType.FONT, font)
    for i=1,NUM_CHAT_WINDOWS do
        local cf = getglobal("ChatFrame"..i)
        local f, s, m = cf:GetFont()    
        cf:SetFont(fontfile, s, m)
    end
end

function Prat_Font:SetFontMode(mode)
    for i=1,NUM_CHAT_WINDOWS do
        local cf = getglobal("ChatFrame"..i)
        local f, s, m = cf:GetFont()    
        cf:SetFont(f, s, mode)
        local c = self.db.profile.outlinecolor
        cf:SetShadowColor(c.r, c.g, c.b, 1)
    end
end

function Prat_Font:GetShadowClr()
    local h = self.db.profile.outlinecolor or {}
    return h.r or 1.0, h.g or 1.0, h.b or 1.0
end
function Prat_Font:SetShadowClr(r,g,b)
    self.db.profile.outlinecolor = self.db.profile.outlinecolor or {}
    local h = self.db.profile.outlinecolor
    h.r, h.g, h.b = r, g, b
    
    self:ConfigureAllChatFrames()
end

function Prat_Font:FCF_SetChatWindowFontSize(chatFrame, fontSize)
	if ( not chatFrame ) then
		chatFrame = FCF_GetCurrentChatFrame();
	end
	if ( not fontSize ) then
		fontSize = this.value;
	end    
    
   self.oldsize[chatFrame:GetID()] = fontSize 

   if self.db and self.db.profile.on then
       self.db.profile.size[chatFrame:GetID()] = fontSize
   end
end

function Prat_Font:SetAutoRestore(val)
    self.db.profile.autorestore = val
    if self.db.profile.autorestore then
    	if not self:IsHooked("UpdateMicroButtons") then self:SecureHook("UpdateMicroButtons", "ConfigureAllChatFrames") end
    else
    	if self:IsHooked("UpdateMicroButtons") then self:Unhook("UpdateMicroButtons") end
    end
end    

function Prat_Font:ModuleGetOption(name)
    if (name == "outlinecolor") then
        local c = self.db.profile.outlinecolor
        self:Debug("getcolor", c.r, c.g, c.b)
        return c.r, c.g, c.b
    else
        return self.super.ModuleGetOption(self, name)
    end
end

function Prat_Font:ModuleSetOption(name, val, v2, v3)
    if (name == "outlinecolor") then
        self:Debug("setcolor", val, v2, v3)
        local c = self.db.profile.outlinecolor
        c.r, c.g, c.b = val, v2, v3
    else
        self.super.ModuleSetOption(self, name, val)
    end
    
    self:ConfigureAllChatFrames()
end
