<?php

namespace KupShop\I18nBundle\Context;

use Doctrine\ORM\EntityManagerInterface;
use KupShop\I18nBundle\Entity\Currency;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Util\Functional\Mapping;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

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

    /** @var SessionInterface */
    protected $session;

    protected $b2bCurrencies = [];

    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('currency', $id);
        }
    }

    public function getDefaultId()
    {
        if (!isset($this->defaultId)) {
            $dbcfg = \Settings::getDefault();
            $this->defaultId = $dbcfg->currency ?? 'CZK';
        }

        return $this->defaultId;
    }

    public function getActive()
    {
        $activeCurrency = parent::getActive();

        if (findModule(\Modules::B2B)) {
            if (Contexts::get(UserContext::class)->isType('b2b') && $activeCurrency->hasB2BSettings()) {
                if (empty($this->b2bCurrencies[$activeCurrency->getId()])) {
                    $this->b2bCurrencies[$activeCurrency->getId()] = $activeCurrency->createB2BInstance();
                }

                return $this->b2bCurrencies[$activeCurrency->getId()];
            }
        }

        return $activeCurrency;
    }

    protected function loadSupported()
    {
        return $this->getAll();
    }

    public function getAll()
    {
        if (!$this->currencies) {
            $currencies = $this->entityManager->getRepository(Currency::class)->findBy([], ['id' => 'ASC']);

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

        return $this->currencies;
    }

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

            return $currency;
        }

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

        $currency = $this->getDefaultId();

        // do not save defaultId in session, so PHPSESSID is not returned. It would break proxy_cache
        if (!findModule(\Modules::PROXY_CACHE)) {
            $this->session->set('currency', $currency);
        }

        return $currency;
    }
}
