<?php

namespace Gls\GlsPoland\Translation;

use Gls\GlsPoland\Translation\TranslationFinder as TranslationFinderPolyfill;
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 PrestaShopBundle\Translation\Provider\TranslationFinderTrait;
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 $e) {
            return null;
        } catch (FileNotFoundException $e) {
            return null;
        }
    }

    /**
     * @return TranslationFinder|LegacyTranslationFinder|TranslationFinderPolyfill
     */
    private function getTranslationFinder()
    {
        if (isset($this->translationFinder)) {
            return $this->translationFinder;
        }

        return $this->translationFinder = $this->createTranslationFinder();
    }

    /**
     * @return TranslationFinder|LegacyTranslationFinder|TranslationFinderPolyfill
     */
    private function createTranslationFinder()
    {
        if (class_exists(TranslationFinder::class)) {
            return new TranslationFinder();
        }

        if (class_exists(LegacyTranslationFinder::class)) {
            return new LegacyTranslationFinder();
        }

        if (trait_exists(TranslationFinderTrait::class)) {
            return new TranslationFinderPolyfill();
        }

        throw new \RuntimeException('Unable to create translation finder.');
    }
}
