<?php

namespace KupShop\KupShopBundle\EventListener;

use KupShop\KupShopBundle\Controller\DynamicRouteController;
use KupShop\KupShopBundle\Event\EarlyDynamicRouteEvent;
use KupShop\KupShopBundle\Util\RequestUtil;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Service\Attribute\Required;

class DynamicRouteControllerListener implements EventSubscriberInterface
{
    #[Required]
    public EventDispatcherInterface $eventDispatcher;

    #[Required]
    public RequestUtil $requestUtil;

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

    public function dynamicDispatch(RequestEvent $event)
    {
        $request = $event->getRequest();
        $controller = $this->requestUtil->getControllerInfo($request);

        if ($controller['controllerFull'] == DynamicRouteController::class) {
            $this->eventDispatcher->dispatch(new EarlyDynamicRouteEvent($request));
        }
    }
}
