-- Copyright (C) 2010 Tyson Brown
-- 
-- This file is part QuestHelper2, an AddOn for World of Warcraft.
-- 
-- QuestHelper2 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 3 of the License, or
-- (at your option) any later version.
-- 
-- QuestHelper2 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 QuestHelper2. If not, see <http://www.gnu.org/licenses/>.

if LibDebug then LibDebug() end
local shared = select(2, ...)

local locales = shared.locale

-- Just an empty table.
local missing_locale = {}
local fallback_locale = locales.enUS
local current_locale = missing_locale

for locale, keys in pairs(locales) do
  -- The locale names and locale tooltips aren't localized per locale,
  -- instead we create keys for these strings and use them for every locale,
  -- as focing users to be able to recognize the name of their locale in another language
  -- is stupid.
  
  local name = keys.SETTING_LOCALE_NAME or locale
  local tooltip = string.format(keys.SETTING_LOCALE_TOOLTIP or fallback_locale.SETTING_LOCALE_TOOLTIP or "%s", name)
  local key = "SETTING_LOCALE_"..locale:upper()
  
  fallback_locale[key] = name
  fallback_locale[key.."_TOOLTIP"] = tooltip
end

shared.onSetting("locale", function (locale)
  current_locale = locales[locale] or missing_locale
end)

-- shared.L is used for translations.
-- Use print(L.key) or print(L.key:format(x,y,z))
shared.L = setmetatable({}, {
  __newindex = function ()
    error("The locale table is read-only.", 2)
  end,
  __index = function (self, key)
    return current_locale[key] or fallback_locale[key] or ("|cffff0000<<%s>>|r"):format(key)
  end,
  __call = function (self, key, ...)
    return self[key]:format(...)
  end
})
