---------------------------------------------------------------------------------
--
-- 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: PratServerNames
Revision: $Revision: 80432 $
Author(s): Curney (asml8ed@gmail.com)
           Krtek (krtek4@gmail.com)
           Sylvanaar (sylvanaar@mindspring.com)

Website: http://www.wowace.com/files/index.php?path=Prat/
Documentation: http://www.wowace.com/wiki/Prat/Integrated_Modules#ServerNames
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 options for replacing server names with abbreviations.
Dependencies: Prat
]]

Prat:AddModuleToLoad(function() 

local PRAT_MODULE = Prat:RequestModuleName("ServerNames")

if PRAT_MODULE == nil then 
    return 
end

local L = Prat:GetLocalizer({})

--@debug@
L:AddLocale("enUS", {
    ["ServerNames"] = true,
    ["Server name abbreviation options."] = true,
    ["Replace"] = true,
    ["Toggle replacing this server."] = true,
    ["Blank"] = true,
    ["Don't display the server name"] = true,
    ["Set"] = true,
    ["Server %d"] = true,
    ["'%s - %s' display settings."] = true,
    ["Use a custom replacement for the server %s text."] = true,
    ["randomclr_name"] = "Random Colors",
    ["randomclr_desc"] = "Use a random color for each server.",
    ["Set color"] = true,
    ["Change the color for this server name"] = true,
    ["Use custom color"] = true,
    ["Toggle useing custom color this server."] = true,
    ["colon_name"] = "Show Colon",
    ["colon_desc"] = "Toggle adding colon after server replacement.",
    ["Unknown Battlegroup"] = true,
    ["Glory-2.0 Not Loaded"] = true,
    ["Click to load Glory-2.0"] = true,
})
--@end-debug@

-- These Localizations are auto-generated. To help with localization
-- please go to http://www.wowace.com/projects/prat-3-0/localization/


--[===[@non-debug@
L:AddLocale("enUS", 
--@localization(locale="enUS", format="lua_table", same-key-is-true=true, namespace="ServerNames")@
)
L:AddLocale("frFR",  
--@localization(locale="frFR", format="lua_table", same-key-is-true=true, namespace="ServerNames")@
)
L:AddLocale("deDE", 
--@localization(locale="deDE", format="lua_table", same-key-is-true=true, namespace="ServerNames")@
)
L:AddLocale("koKR",  
--@localization(locale="koKR", format="lua_table", same-key-is-true=true, namespace="ServerNames")@
)
L:AddLocale("esMX",  
--@localization(locale="esMX", format="lua_table", same-key-is-true=true, namespace="ServerNames")@
)
L:AddLocale("ruRU",  
--@localization(locale="ruRU", format="lua_table", same-key-is-true=true, namespace="ServerNames")@
)
L:AddLocale("zhCN",  
--@localization(locale="zhCN", format="lua_table", same-key-is-true=true, namespace="ServerNames")@
)
L:AddLocale("esES",  
--@localization(locale="esES", format="lua_table", same-key-is-true=true, namespace="ServerNames")@
)
L:AddLocale("zhTW",  
--@localization(locale="zhTW", format="lua_table", same-key-is-true=true, namespace="ServerNames")@
)
--@end-non-debug@]===]





--

--

--

--

--


local module = Prat:NewModule(PRAT_MODULE)

Prat:SetModuleDefaults(module.name, {
	profile = {
	    on = true,
	    space = true,
	    colon = true,
	
	    chanSave = {},
	   
	    serveropts = { 
	        ["*"] = {
	            replace = false,
	            customcolor = false,
	            shortname = "",
	            color = {
	                r = 0.65,
	                g = 0.65,
	                b = 0.65,
					a = 1,
	            },   
	        },
	    },
	
	    randomclr = false,
	}
} )

local serverPlugins = { servers={} }

Prat:SetModuleOptions(module.name, {
        name = L["ServerNames"],
        desc = L["Server name abbreviation options."],
        type = "group",
		plugins = serverPlugins,
        args = {
			randomclr = {
				type = "toggle",
				name = L["randomclr_name"],
				desc = L["randomclr_desc"],
				order = 250
			}
        }
    }
)

-- build the options menu using prat templates
--module.toggleOptions = { optsep_sep = 240, randomclr = 250}
--module.toggleOptions = { optsep_sep = 229, space = 230, colon = 240 }

--local server_tags = {
--    ["Normal"] = "(E)",
--    ["PvP"] = "(P)",
--    ["RP"] = "(R)",
--    ["RP-PvP"] = "(PR)",
--}
--
--local server_desctags = {
--    ["Normal"] = "PvE",
--    ["PvP"] = "PvP",
--    ["RP"] = "RP",
--    ["RP-PvP"] = "RPPvP",
--}

local CLR = Prat.CLR
local function Server(server, text) return Prat.CLR:Colorize(module:GetServerCLR(server), text or server) end

-- Get the key for the server specified, safe to pass this nil and "", if no key then it returns nil
local function GetServerKey(server) 
	if server and strlen(server)>0 then 
		return server:gsub(" ", ""):lower() 
	end 
end

function module:GetServerSettings(serverKey)
    opts = self.db.profile.serveropts[serverKey]
	if not opts then
		self.db.profile.serveropts[serverKey] = {}
		opts = self.db.profile.serveropts[serverKey]
	end
	
	return opts
end

--[[------------------------------------------------
    Module Event Functions
------------------------------------------------]]--
function module:OnModuleEnable()
    self:BuildServerOptions()
    Prat.RegisterChatEvent(self, "Prat_PreAddMessage")
end

function module:OnModuleDisable()
    Prat.UnregisterAllChatEvents(self)
end

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

-- replace text using prat event implementation
function module:Prat_PreAddMessage(e, m, frame, event)
    local serverKey = GetServerKey(m.SERVER) 
    local opts = serverKey and self:GetServerSettings(serverKey)

    if opts and opts.replace then
        m.SERVER = opts.shortname
    end  

    if m.SERVER and strlen(m.SERVER)>0 then
        m.SERVER = Server(serverKey, m.SERVER)
    end

    if not (m.SERVER and strlen(m.SERVER)>0) then
		local s = Prat.SplitMessage        
		s.SERVER, s.sS, s.Ss = "", "", ""
    end
end

local serverHashes = setmetatable({}, { __mode = "kv", __index = function(t,k) t[k] = CLR:GetHashColor(k) return t[k] end })
local serverColors = setmetatable({}, { __mode = "kv", __index = function(t,k) t[k] = CLR:GetHexColor(k) return t[k] end })

function module:GetServerCLR(server)
    local serverKey = GetServerKey(server) 

    if serverKey then
        local opts = self:GetServerSettings(serverKey)
    
        if opts and opts.customcolor then
            return serverColors[opts.color]        
        elseif self.db.profile.randomclr then 
            return serverHashes[serverKey]
        end
    end

    return CLR.COLOR_NONE
end

--[[------------------------------------------------
    Menu Builder Functions
------------------------------------------------]]--

function module:BuildServerOptions()   
--    if Glory then 
--        if opts.noglory then opts.noglory = nil end
--        local serverList = {}
--        local homeservName = GetRealmName()
--        Glory:GetBattlegroupServers(nil, serverList)
--        
--        local scount = 0
--
--        local serverKey, serverType
--        for _,v in pairs(serverList) do
--        -- Since we dont detect the home server, dont offer an option
--            if v ~= homeservName then
--                serverKey = GetServerKey(v)   
--                serverType = Glory:GetServerType(v)
--                self:CreateServerOption(self.moduleOptions.args, v, serverKey, serverType)
--                
--                scount = scount + 1
--            end
--        end
--        
--        if scount == 0 then 
--            opts.noservers = {}
--            opts.noservers.type = 'header'
--            opts.noservers.name = L["Unknown Battlegroup"]
--        else
--            opts.noservers = nil
--        end
--    else
--
--    end
    
    
end



--
--
-- "-Name(type)" is how we have it
--
--  so provide
--
--   %S = Full Server Name
--   %s = Abbreviated Server Name
--   %T = Full Realm Type eg PvP
--   %t = Abbreviated Realm Type e.g P
--
--  So the default format is:
--
--      -%S(%t)
--
--   We can support a coloring syntax
--   which can say use the color of
--   (some other field) Here, we can 
--   Set the color of the server to use
--   the color value of the realm type
--   
--
local t_sort = {}
function module:UpdateServerMenu()
--    for k,v in pairs(args) do
--        if v.name_org then
--            local opts = self.db.profile.serveropts[k]
--
--            v.name = CLR:Server(v.name_org)
--            if opts and opts.replace and opts.shortname and strlen(opts.shortname) > 0 then
--                v.name = v.name .. " - (" .. CLR:Server(v.name_org, opts.shortname) .. ")"
--            end
--
--            v.args.setname.name = v.name
--            t_sort[#t_sort+1] = k
--        end
--    end
--
--    -- Now it must be sorted   
--    table.sort(t_sort)
--
--    -- Now apply ordering
--    local o = 10
--    for i,k in ipairs(t_sort) do
--        t_sort[i] = nil
--        args[k].order = o
--        o = o + 1
--    end
end


function module:CreateServerOption(args, servername, serverkey, servertype)
--    local name = serverkey
--    local text = servername
--    local type = text
--
--
--
--    args[name] = {
--        name = CLR:Server(text),
--        name_org = text,
--        type_org = servertype,
--        desc = string.format(L["'%s - %s' display settings."], text, server_desctags[servertype]),
--        type = "group",
--        args = {
--            setname = {
--                name = CLR:Server(text),
--                desc = string.format(L["Use a custom replacement for the server %s text."], text),
--                order = 10,
--                type = "text",
--                usage = "<string>",
--                get = function() return self.db.profile.serveropts[name].shortname end,
--                set = function(v) self.db.profile.serveropts[name].shortname = v end
--            },
--            optsep20 = {
--                order = 20,
--                type = 'header',
--            },
--            usecustomcolor = {
--                name = L["Use custom color"],
--                desc = L["Toggle useing custom color this server."],
--                type = "toggle",
--                order = 24,
--                get = function() return self.db.profile.serveropts[name].customcolor end,
--                set = function(v) self.db.profile.serveropts[name].customcolor = v end
--            },
--            customcolor = {
--                name = L["Set color"],
--                desc = L["Change the color for this server name"],
--                type = "color",
--                order = 25,
--                get = function() local c = self.db.profile.serveropts[name].color
--                         return c.r, c.g, c.b end,
--                set = function(r, g, b, a) local c = self.db.profile.serveropts[name].color
--                        c.r, c.g, c.b = r, g, b end,
--                disabled = function() if not self.db.profile.serveropts[name].customcolor then return true else return false end end,
--            },
--            optsep27 = {
--                order = 27,
--                type = 'header',
--            },
--            replace = {
--                name = L["Replace"],
--                desc = L["Toggle replacing this server."],
--                type = "toggle",
--                order = 30,
--                get = function() return self.db.profile.serveropts[name].replace  end,
--                set = function(v) self.db.profile.serveropts[name].replace  = v end,
--            },
--            off = {
--                name = L["Blank"],
--                desc = L["Don't display the server name"],
--                type = "execute",
--                order = 40,
--                func = function() self.db.profile.serveropts[name].shortname  = ""  end
--            }
--        }
--    }
end


  return
end ) -- Prat:AddModuleToLoad