<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\EventListener;

use CpCreation\VitiCore\Product\Repository\ProductPriceGroupRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class GroupListener implements EventSubscriberInterface
{
    private $session;
    private $productPriceGroupRepository;

    public function __construct(SessionInterface $session, ProductPriceGroupRepository $productPriceGroupRepository)
    {
        $this->session                     = $session;
        $this->productPriceGroupRepository = $productPriceGroupRepository;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => [['onKernelRequest', 10]],
        ];
    }

    public function onKernelRequest(RequestEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }
        if (!$this->session->get("groupPrice")) {
            $defaultGroup = $this->productPriceGroupRepository->findOneBy(["byDefault" => true]);
            if ($defaultGroup) {
                $this->session->set("groupPrice", $defaultGroup->getId()->toString());
                $this->session->set("groupByDefault", true);
                $this->session->set("codePrice", null);
            }
        }
    }
}
