<?php

namespace External\SprintBundle\Context;

use Doctrine\ORM\EntityManagerInterface;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Context\UserContext;
use Query\Operator;

class PricelistContext extends \KupShop\PricelistBundle\Context\PricelistContext
{
    public const EUR_PRICELIST_ID = 1;

    protected $currencyContext;

    private $userContext;

    public function __construct(EntityManagerInterface $em, CurrencyContext $currencyContext, UserContext $userContext)
    {
        $this->currencyContext = $currencyContext;
        $this->userContext = $userContext;

        parent::__construct($em);
    }

    public function loadActive()
    {
        if ($userID = $this->userContext->getActiveId()) {
            if ($pricelistID = sqlQueryBuilder()->select('id_pricelist')->from('users')
                ->where(Operator::equals(['id' => $userID]))->execute()->fetchColumn()) {
                return $pricelistID;
            }
        }

        if ($this->currencyContext->getActiveId() == 'EUR') {
            return self::EUR_PRICELIST_ID;
        }

        return parent::loadActive();
    }
}
