<?php

namespace Gls\GlsPoland\Translation;

use PrestaShop\PrestaShop\Core\Exception\FileNotFoundException;
use PrestaShop\PrestaShop\Core\Translation\Exception\TranslationFilesNotFoundException;
use PrestaShop\PrestaShop\Core\Translation\Storage\Finder\TranslationFinder;
use PrestaShopBundle\Translation\Provider\TranslationFinder as LegacyTranslationFinder;
use Symfony\Component\Translation\MessageCatalogue;

trait TranslationLoaderTrait
{
    private $translationFinder;

    /**
     * @param string $directory
     * @param string $locale
     *
     * @return MessageCatalogue|null
     */
    private function loadTranslations($directory, $locale)
    {
        $translationsDirectory = rtrim($directory) . \DIRECTORY_SEPARATOR . $locale;

        if (!is_dir($translationsDirectory)) {
            return null;
        }

        try {
            return $this->getTranslationFinder()->getCatalogueFromPaths([$translationsDirectory], $locale);
        } catch (TranslationFilesNotFoundException|FileNotFoundException $e) {
            return null;
        }
    }

    /**
     * @return TranslationFinder|LegacyTranslationFinder
     */
    private function getTranslationFinder()
    {
        return $this->translationFinder ?? ($this->translationFinder = class_exists(TranslationFinder::class)
            ? new TranslationFinder()
            : new LegacyTranslationFinder()
        );
    }
}
