<?php

class Core_Translate
{

    /**
     * Translated files location
     */
    protected $_location;

    /**
     *
     * @var string
     */
    protected static $_locale;

    /**
     * Translation buffer
     */
    protected static $_translations = array();

    /**
     * Translate given string using translation library file
     *
     * @param   string  $string
     * @param   string  $locale
     *
     * @return  string
     */
    public static function translate($string, $locale = null)
    {
        if (null === $locale) {
            $locale = self::getLocale();
        }

        if ($locale == Core_Application::get('config')->app->default_language) {
            return $string;
        }

        $translations   = self::getTranslations($locale);

        // return translated string if it exists
        $stringHash = md5($string);
        if (array_key_exists($stringHash, $translations) && strlen($translations[$stringHash][$locale])) {
            return $translations[$stringHash][$locale];
        }

        if (Core_Application::get('request')->get('untranslated')) {
            $string = sprintf('<span class="untranslated blink">%s</span>', $string);
        }

        // Translation does not exist, return original string
        return $string;
    }

    /**
     * Get locale from application using Core_Request
     *
     * @return string
     */
    public static function getLocale()
    {
        if (null === self::$_locale) {
            /*
            $request    = Core_Application::get('request');
            $lang = $request->get('lang');
            self::$_locale = $lang;
            */
            self::$_locale = Core_Application::getInstance()->getLanguage();
        }

        return self::$_locale;
    }

    /**
     *
     * @param   string  $locale
     *
     * @return  array
     */
    public static function getTranslations($locale)
    {
        if (!isset(self::$_translations[$locale])) {

            // is this language enabled?
            if (!array_key_exists($locale, Core_Application::get('config')->app->languages->toArray())) {
                throw new Exception('Language not found, or disabled: '. $locale .'. Check your configuration files.');
            }

            $translation_file = Core_Application::getInstance()->getRoot() . '/var/locale/translation.' . $locale . '.php';

            // do we have the file, parser created it or not?
            if (!file_exists($translation_file)) {
                throw new RuntimeException('Translation file not found: translation.' . $locale . '.php');
            }

            self::$_translations[$locale] = require_once $translation_file;
        }

        return self::$_translations[$locale];
    }


}