require "prefs"

local language = ''

local lang_map = {
  ['ru'] = 'ru',
  ['by'] = 'ru',
  ['uk'] = 'ru'
}

local lang_list = {
  {'en', 'English'},
  {'ru', 'Русский'},
}

local default_locale = {};

local locale = {};

function translate_now(domain, key, subst)
  local lang = language
  if lang == '' then
    if lang_map[LANG] then
      lang = lang_map[LANG];
    else
      lang = 'en';
    end;
  end;
  local val = key;
  local table = locale[domain];
  local default_table = default_locale[domain];
  if table[key] ~= nil  then
    if table[key] ~= nil then
      val = table[key];
    elseif default_table[key] ~= nil then
      val = default_table[key]
    end;
  end
  
  if subst then
    for k, s in pairs(subst) do
      val = string.gsub(val, '%%' .. k .. '%%', s);
    end;
  end;
  
  return val
end;

function translate(domain, key, subst)
  return function()
    return translate_now(domain, key, subst);
  end;
end;

function set_language(lng)
  language = lng;
  prefs.language = lng;
  prefs:store();
  
  dofile('translation/' .. get_language() .. '.lua');
end;

obj {
  nam = '@set_language';
  act = function(s, w)
    set_language(w);
    walk(here())
  end;
}

function get_language_saved()
  return language;
end;

function get_language()
  if language and language ~= '' then
    return language;
  elseif lang_map[LANG] then
    return lang_map[LANG];
  else
    return lang_list[1][1];
  end;
end;

function get_default_language()
  return lang_list[1][1];
end;

function get_language_list()
  return lang_list;
end;

function set_locale_data(data)
  locale = data;
end;

std.mod_init(function()
  dofile('translation/' .. get_language_list()[1][1] .. '.lua');
  default_locale = locale;
  prefs:load();
  if prefs.language then
    language = prefs.language;
  else
    prefs.language = '';
  end;
  
  dofile('translation/' .. get_language() .. '.lua');
end)


