<?php


namespace App\Listener;


use App\Service\KeyLighterVersioner;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

class KeyLighterVersionListener
{
    private $versioner;

    /**
     * KeyLighterVersionListener constructor.
     *
     * @param $versioner
     */
    public function __construct(KeyLighterVersioner $versioner)
    {
        $this->versioner = $versioner;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        $cookie  = $event->getRequest()->cookies->get('keylighter_version', 'dev-master');
        $version = $event->getRequest()->query->get('keylighter', $cookie);

        $this->versioner->load($version);
    }

    public function onKernelResponse(ResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        if ($event->getRequest()->query->has('keylighter')) {
            $cookie = new Cookie('keylighter_version', $this->versioner->getCurrent());
            $event->getResponse()->headers->setCookie($cookie);
        }
    }
}
