<?php namespace Concore\Foundation\Translation;

use Illuminate\Translation\Translator as LaravelTranslator;

class Translator extends LaravelTranslator {

    /**
     * Get the translation for the given key.
     *
     * @param  string  $key
     * @param  array   $replace
     * @param  string  $locale
     * @return string
     */
    public function get($key, array $replace = array(), $locale = null)
    {
        list($namespace, $group, $item) = $this->parseKey($key);

        $line = $this->getLineFromLocale($namespace, $group, $item, $replace, $locale);

        // If the line doesn't exist, we will return back the key which was requested as
        // that will be quick to spot in the UI if language keys are wrong or missing
        // from the application's language files. Otherwise we can return the line.
        if (is_null($line)) {
            if (!($namespace == '*' && $group == 'default')) {
                $item = $group.$item;
                $line = $this->getLineFromLocale($namespace, 'default', $item, $replace, $locale);
            }
            if (is_null($line)) {
                if($replace) {
                    $key = $this->makeReplacements($key, $replace);
                }
                return $key;
            }
        }

        return $line;
    }

    public function getLineFromLocale($namespace, $group, $item, array $replace = array(), $locale = null) {
        $line = null;

        // Here we will get the locale that should be used for the language line. If one
        // was not passed, we will use the default locales which was given to us when
        // the translator was instantiated. Then, we can load the lines and return.
        foreach ($this->parseLocale($locale) as $locale)
        {
            $this->load($namespace, $group, $locale);

            $line = $this->getLine(
                $namespace, $group, $locale, $item, $replace
            );

            if ( ! is_null($line)) break;
        }

        return $line;
    }

}