<?php

namespace KupShop\I18nBundle\Context;

use Doctrine\ORM\EntityManagerInterface;
use KupShop\I18nBundle\Entity\Language;
use KupShop\KupShopBundle\Util\Functional\Mapping;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class LanguageContext extends \KupShop\KupShopBundle\Context\LanguageContext
{
    /** @var EntityManagerInterface */
    protected $entityManager;
    /**
     * @var SessionInterface
     */
    protected $session;

    public function __construct(EntityManagerInterface $entityManager, SessionInterface $session)
    {
        parent::__construct();

        $this->entityManager = $entityManager;
        $this->session = $session;
    }

    public function remember(string $id)
    {
        if ($this->validate($id)) {
            $this->session->set('language', $id);
        }
    }

    public function getAll(): array
    {
        if ($this->languages !== null) {
            return $this->languages;
        }

        $languages = $this->entityManager->getRepository(Language::class)->findAll();

        return $this->languages = Mapping::mapKeys($languages, function ($key, Language $value) {
            return [$value->getId(), $value];
        });
    }

    protected function loadSupported()
    {
        $languages = $this->entityManager->getRepository(Language::class)->findBy(['active' => true]);

        return Mapping::mapKeys($languages, function ($key, Language $value) {
            return [$value->getId(), $value];
        });
    }

    protected function loadActive()
    {
        // HACK: get from GET parameter
        $lang = getVal('lang');
        if ($lang && $this->validate($lang)) {
            $this->session->set('language', $lang);

            return $lang;
        }

        if ($lang = $this->session->get('language')) {
            return $lang;
        }

        return $this->getDefaultFromConfig();
    }
}
