<?php

  /**
   * Module de gestion des langues pour Onyx
   *
   * @link http://onyx.halo-battle.fr/
   * @authour 2011 Némunaire <nemunaire@gmail.com>
   * @version 2.0
   * @see The GNU Public License (GPL)
   * Last modified: 13/02/2011
   */

  /**
   * 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 3 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, see <http://www.gnu.org/licenses/>.
   */

if(!defined("ONYX")) exit;

if(!is_readable(ONYX."lang/".$OPT["type"]."/"))
  {
    if(is_readable(ONYX."lang/".$OPT["type"].".xml"))
      trigger_error("You run the version 2 of Onyx language module. Convert your XML language file into JSON files (see Onyx website  : http://onyx.halo-battle.fr/).", E_USER_ERROR);
    else
      trigger_error('Language directory not found or unreadable.', E_USER_ERROR);
  }

define('LANG', $OPT['type']);

/**
 * Classe gérant les chargements dynamiques des fichiers de langue
 */
class Lang
{
  private static $loaded = array();

  private static function loadFile($file, $lang = LANG)
  {
    if (is_array($file))
      $filename = ONYX."lang/".$lang."/".implode("/", $file).".json";
    else
      $filename = ONYX."lang/".$lang."/".$file.".json";

    if(!is_readable($filename))
      {
	if (is_array($file))
	  trigger_error("Language file $lang/".implode("/", $file)." not found or unreadable.", E_USER_ERROR);
	else
	  trigger_error("Language file $lang/$file not found or unreadable.", E_USER_ERROR);
      }

    //Lang::loaded[md5($filename)] = json_decode(file_get_contents($filename), true);
    Lang::$loaded[$filename] = json_decode(file_get_contents($filename), true);
  }

  public static function getText($file, $path, $lang = LANG)
  {
    if (is_array($file))
      $filename = ONYX."lang/".$lang."/".implode("/", $file).".json";
    else
      $filename = ONYX."lang/".$lang."/".$file.".json";
    //$filename = md5($filename);

    if (empty(Lang::$loaded[$filename]))
      Lang::loadFile($file, $lang);

    if (!is_array($path) && preg_match("#/#", $path))
	$path = explode("/", $path);

    if (is_array($path))
      {
	$ret = Lang::$loaded[$filename];

	foreach($path as $p)
	  {
	    $ret = $ret[$p];
	  }

	return $ret;
      }
    else
      return Lang::$loaded[$filename][$path];
  }
}

?>