<?php

namespace App\EventListener;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Access\Access;
use App\Service\Doctrine\FiltersConfigurationService;
use App\Service\OnStart\SessionParametersSetter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Bundle\SecurityBundle\Security;
use App\Service\Utils\StringsUtils;

class OnKernelRequestPreRead implements EventSubscriberInterface
{
    public function __construct(
        private RequestStack $requestStack,
        private Security $security,
        private FiltersConfigurationService $filtersConfigurationService
    ) {}

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

    public function onKernelRequest(RequestEvent $event): void {
        if (!$event->isMainRequest()) {
            // don't do anything if it's not the main request
            return;
        }

        $mainRequest = $this->requestStack->getMainRequest();

        /** @var Access $access */
        $access = $this->security->getUser();
        if ($access) {

            $timeConstraintEnabled = (bool) StringsUtils::unquote(
                $this->requestStack->getMainRequest()->get('_time_constraint', true)
            );

            if ($timeConstraintEnabled) {
                $this->filtersConfigurationService->configureTimeConstraintFilters($access->getId());
            }
        }
    }
}
