<?php

namespace QUI\Setup\Locale;

use function class_exists;
use function dirname;

class Locale
{
    protected $Locale = null;

    protected $mode = null;

    const MODE_GET_TEXT = 0; // deprecated
    const MODE_INI_FILES = 1;

    /**
     * Constructor.
     *
     * @param string $lang - Culturecode. E.G.: en
     *
     * @throws LocaleException
     */
    public function __construct($lang)
    {
        if (!class_exists('IniLocale')) {
            require_once dirname(__FILE__) . '/IniLocale.php';
        }

        $this->Locale = new IniLocale($lang);
    }

    /**
     * Returns a translated String. Returns a fallback if translation is not found.
     *
     * @param string $string - The key to search for in the translation files.
     * @param string $fallback - The fallback to use, if the key was not found
     *
     * @return string - A translated String.
     */
    public function getStringLang($string, $fallback = "")
    {
        return $this->Locale->getStringLang($string, $fallback);
    }

    /**
     * Sets the language to use for translations
     *
     * @param string $lang - Culturecode to use. EG en
     *
     * @throws LocaleException
     */
    public function setLanguage($langCode)
    {
        try {
            $this->Locale->setLanguage($langCode);
        } catch (\Exception $Exception) {
            // Fallback if all other fallbacks failed!
            $this->Locale = new IniLocale('en');
            $this->mode = self::MODE_INI_FILES;
            throw new LocaleException(
                'Could not switch to the desired locale \'' . $langCode . '\'. Using english translation as fallback.'
            );
        }
    }

    /**
     * @return string
     */
    public function getCurrent()
    {
        return $this->Locale->getCurrent();
    }

    /**
     * This will read all localization variables from the .po file for the current language
     *
     * @return array
     * @throws LocaleException
     */
    public function getAll()
    {
        return $this->Locale->getAll();
    }

    /**
     * Detects the appropriate mode, which the Locale should use.
     *
     * @return int
     */
    protected function detectMode()
    {
        return self::MODE_INI_FILES;
    }
}
