<?php declare(strict_types=1);

// composer require symfony/translation
// Load Composer's autoloader
require __DIR__ . '/../../vendor/autoload.php';

use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\Loader\ArrayLoader;
use Symfony\Component\Translation\Loader\PhpFileLoader;

use Symfony\Config\FrameworkConfig;    // for default locale

// Translator supporting the langauges English and German.
final class QrbTranslator
{
    private const TRANSLATION_DIR = __DIR__ . "/../../translations/";
    
    private Translator $translator;

    
    // Loads the message files.
    public function __construct()
    {
        // Set Error Handler
        set_error_handler(
            function($errno, $errstr, $errfile, $errline)
            {
                throw new ErrorException($errstr, $errno, 0, $errfile, $errline);     
            }
        );
        
        $this->translator = new Translator("en");
        $this->translator->addLoader('php', new PhpFileLoader());
        
        $messageFiles = $this->findTranslationFiles(QrbFiles::fixPath(self::TRANSLATION_DIR));
        
        foreach ($messageFiles as $language => $path)
        {
            $this->translator->addResource('php', $path, $language);
        }
        
        $this->translator->setFallbackLocales(['en']);
    }

    // Scans the given directory for message files.
    // Returns associative array with:
    //   language:  2 character language code    
    //   path:      path to message file
    // public for unit test
    public function findTranslationFiles(string $directory) : array // of string (language) => string (path)
    {
        $dirIt  = new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS);
        $fileIt = new RecursiveIteratorIterator($dirIt, RecursiveIteratorIterator::CHILD_FIRST);
        $result = array();

        $count = 1;
        foreach ($fileIt as $file)
        {
            if (!$file->isFile())           continue;
            
            $parts = explode(".", $file->getFilename());
            if (count($parts) != 3)         continue;
            if ($parts[0] != "messages")    continue;
            if (strlen($parts[1]) != 2)     continue;
            if ($parts[2] != "php")         continue;
            
            $result[$parts[1]] = $file->getRealPath();
        }
        
        return $result;
    }

    // Sets the locale.    
    public function setLocale(string $locale)
    {
        $this->translator->setlocale($locale);
    }

    // Translates the given key into the current user language using the locale set by setLocale().
    // Returns translation.
    public function xl(string $key) : string
    {
        return $this->translator->trans($key);
    }
}

?>
