<?php
/*
 * Resource helper
 */
class res_Resource {
    private static $defaultLanguage = 'en';
    protected $name;
    protected $language;
    protected $bundle = NULL;

    public function __construct($name, $language = NULL) {
        $this->name = $name;
        $this->language = $language != NULL ? $language : res_Resource::getDefaultLanguage();
        $this->load();
    }
	protected function load() {
        $content = file_get_contents($this->getFilename());
        //$this->bundle = json_decode($content, true);
        $this->bundle = array();
        $doc = new DOMDocument();
        $doc->loadXML($content);
        $node = $doc->documentElement;
        $count = $node->childNodes->length;
        for ($i = 0; $i < $count; $i++) {
            $item = $node->childNodes->item($i);
            if (($item->nodeType == XML_ELEMENT_NODE) && ($item->nodeName == 'entry')) {
                $this->bundle[$item->getAttribute('key')] = $item->nodeValue;
            }
        }
    }
    public function getFilename() {
        return $this->name . '.' . $this->language . '.xml';
    }
    public function get($key) {
        if (array_key_exists($key, $this->bundle)) {
            return $this->bundle[$key];
        }
        return $key;
        //throw new Exception('Key "' . $key . '" not found.');
    }
    public function getf() {
        $numargs = func_num_args();
        if ($numargs < 1) {
            throw new Exception('Missing arguments');
        }
        $key = func_get_arg(0);
        $format = $this->get($key);
        if ($numargs == 1) {
            return $format;
        }
        $args = array();
        for ($i = 1; $i < $numargs; $i++) {
            $arg = func_get_arg($i);
            $args[] = $arg;
        }
        return vsprintf($format, $args);
    }
    public static function setDefaultLanguage($language) {
        self::$defaultLanguage = $language;
    }
    public static function getDefaultLanguage() {
        return self::$defaultLanguage;
    }
}
?>