<?php

namespace External\SprintBundle\Context;

use Doctrine\ORM\EntityManagerInterface;
use KupShop\I18nBundle\Entity\Currency;
use KupShop\KupShopBundle\Context\CountryContext;
use KupShop\KupShopBundle\Context\UserContext;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class CurrencyContext extends \KupShop\I18nBundle\Context\CurrencyContext
{
    protected $config;

    protected $domains = [];
    /**
     * @var RequestStack
     */
    private $requestStack;

    private CountryContext $countryContext;
    public UserContext $userContext;

    public function __construct(
        EntityManagerInterface $entityManager,
        SessionInterface $session,
        RequestStack $requestStack,
        CountryContext $countryContext,
    ) {
        parent::__construct($entityManager, $session);

        $this->requestStack = $requestStack;
        $this->countryContext = $countryContext;
    }

    public function setDomains(array $domains): CurrencyContext
    {
        $this->domains = $domains;

        return $this;
    }

    protected function loadActive()
    {
        $user = $this->userContext->getActive();

        if ($user) {
            $user->fetchAddresses();
            if ($country = $user->invoice['country'] ?? false) {
                if ($this->validate($country)) {
                    switch ($country) {
                        case 'CZ':
                            return 'CZK';
                        default:
                            return 'EUR';
                    }
                }
            }
        }

        switch ($this->countryContext->getActiveId()) {
            case 'CZ':
                return 'CZK';
            default:
                return 'EUR';
        }
    }

    /**
     * @return Currency
     */
    public function getDefault()
    {
        return $this->getAll()[$this->getDefaultId()];
    }

    /**
     * @required
     */
    public function setUserContext(UserContext $userContext)
    {
        $this->userContext = $userContext;
    }

    public function setConfig($config): void
    {
        $this->config = $config;
    }
}
