<?php

// Gettext text domain
define('TEXT_DOMAIN', 'DEFAULT');

/**
 * List available translation languages
 *
 * @param $as_locales boolean  If true, locale names will be return instead
 *                             of primary languages (optional, default: false)
 *
 * @return array Array of available translation languages (or locales)
 */
function get_available_langs($as_locales=false) {
  global $root_lang_dir;
  if (!is_dir($root_lang_dir))
    logging('FATAL', "Root land directory not found ($root_lang_dir)");
  $langs = array(($as_locales?'en_US.UTF8':'en'));
  if ($dh = opendir($root_lang_dir)) {
    while (($file = readdir($dh)) !== false) {
      if (!is_dir($root_lang_dir . '/' . $file) || in_array($file, array('.', '..')))
        continue;
      if ($as_locales) {
        $langs[] = $file;
        continue;
      }
      $lang = Locale::getPrimaryLanguage($file);
      if (!in_array($lang, $langs))
        $langs[] = $lang;
    }
    closedir($dh);
  }
  $langs = array_unique($langs);
  logging('TRACE', 'Available '.($as_locales?'locales':'languages').': '.implode(', ', $langs));
  return $langs;
}

/**
 * Get locale name corresponding to specified translation language
 *
 * @param  $lang string The translation language
 * @param  $default string|null Default locale name to return if any available translation
 *                              locales matched with the specified language
 *                              (optional, default: $default_locale)
 * @return string Corresponding locale
 */
function lang2locale($lang, $default=null) {
  global $default_locale;
  if (is_null($default))
    $default = $default_locale;
  foreach (get_available_langs(true) as $locale) {
    if (strpos($locale, $lang) === false)
      continue;
    return $locale;
  }
  return $default;
}

/**
 * Helper function: just mark message for translation
 *
 * @param  string $msg  The message to translate
 *
 * @return string The message without transformation
 */
function ___($msg) {
  return $msg;
}

/**
 * Initialize translation system
 *
 * Detect best translation language and configure the translation
 * system.
 *
 * @return void
 */
function init_translation() {
  global $root_dir_path, $root_lang_dir, $default_locale, $smarty;
  $root_lang_dir = "$root_dir_path/lang";

  if (!class_exists('Locale')) {
    logging('ERROR', 'Locale PHP class does not exist. May be php-intl is not installed?');
    return;
  }

  $available_langs = get_available_langs();
  if (php_sapi_name() != "cli") {
    if (isset($_REQUEST['lang']) && in_array($_REQUEST['lang'], $available_langs)) {
      $lang = $_REQUEST['lang'];
      logging('TRACE', "Select lang from request parameter: '$lang'");
    }
    elseif (isset($_SESSION['lang']) && in_array($_SESSION['lang'], $available_langs) && !isset($_REQUEST['reset_lang'])) {
      $lang = $_SESSION['lang'];
      logging('TRACE', "Restore lang from session: '$lang'");
    }
    else {
      $lang = Locale::lookup(
        get_available_langs(),
        Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']),
        true,
        Locale::getPrimaryLanguage($default_locale)
      );
      logging('TRACE', "Best lang found is '$lang'");
    }
  }
  else {
    $lang = null;
    $sys_current = getenv('LC_ALL');
    if (!$sys_current)
      $sys_current = getenv('LANG');
    if ($sys_current)
      $lang = Locale::getPrimaryLanguage($sys_current);
    if (is_null($lang)) {
      logging('TRACE', 'No configured lang detected from CLI env, use default.');
      $lang = Locale::getPrimaryLanguage($default_locale);
    }
    else
      logging('TRACE', "Lang detected from CLI env : '$lang'");
  }

  // Keep selected lang in session
  $_SESSION['lang'] = $lang;

  $locale = lang2locale($lang);
  logging('TRACE', "Matching locale found with language '$lang' is '$locale'");

  // Gettext firstly look the LANGUAGE env variable, so set it
  if (!putenv("LANGUAGE=$locale"))
    logging('ERROR', "Fail to set LANGUAGE variable in environnement to '$locale'");

  // Set the locale
  if (setlocale(LC_ALL, $locale) === false)
    logging('ERROR', "An error occured setting locale to '$locale'");

  // Configure and set the text domain
  $fullpath = bindtextdomain(TEXT_DOMAIN, $root_lang_dir);
  logging('TRACE', "Text domain fullpath is '$fullpath'.");
  logging('TRACE', "Text domain is '".textdomain(TEXT_DOMAIN)."'.");
  logging('TRACE', "Test: "._('Hello world !'));

  // JS translation file
  $json_translation_file = "translations/$lang.json";
  if (php_sapi_name() != "cli" && is_file("$root_dir_path/public_html/$json_translation_file")) {
    add_js_file("lib/babel.js");
    add_js_file("js/translation.js");
    $smarty->assign('lang', $lang);
  }
}
