<?php

namespace KupShop\I18nBundle\Util;

use KupShop\I18nBundle\Entity\Language;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Functional\Mapping;
use KupShop\KupShopBundle\Util\Locale\LanguageSwitcher;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\Routing\RouterInterface;

class LanguageAwareRoutingCacheWarmer implements CacheWarmerInterface
{
    /**
     * @var LanguageContext
     */
    private $languageContext;
    /**
     * @var RouterInterface
     */
    private $router;
    /**
     * @var LanguageSwitcher
     */
    private $languageSwitcher;

    public function __construct(LanguageContext $languageContext, RouterInterface $router, LanguageSwitcher $languageSwitcher)
    {
        $this->languageContext = $languageContext;
        $this->router = $router;
        $this->languageSwitcher = $languageSwitcher;
    }

    /**
     * Checks whether this warmer is optional or not.
     *
     * Optional warmers can be ignored on certain conditions.
     *
     * A warmer should return true if the cache can be
     * generated incrementally and on-demand.
     *
     * @return bool true if the warmer is optional, false otherwise
     */
    public function isOptional()
    {
        return true;
    }

    /**
     * Warms up the cache.
     *
     * @param string $cacheDir The cache directory
     */
    public function warmUp($cacheDir)
    {
        $languages = [];
        try {
            $languages = $this->languageContext->getSupported();
        } catch (\Exception $e) {
            // Try to take languages from env
            if (getenv('LANGUAGES')) {
                $languages = Mapping::mapKeys(explode(',', getenv('LANGUAGES')), function ($index, $lang) {
                    $language = new Language();
                    $language->setId($lang);

                    return [$lang, $language];
                });

                $reflection = new \ReflectionClass($this->languageContext);
                $property = $reflection->getProperty('supported');
                $property->setAccessible(true);
                $property->setValue($this->languageContext, $languages);
            }
        }

        foreach ($languages as $language) {
            $this->router->generateInLanguage($language->getId(), 'home');
            $this->router->matchInLanguage($language->getId(), '/');
        }
    }
}
