<?php
declare(strict_types=1);

namespace App\EventListener\DoctrineFilter;

use App\Entity\Access\Access;
use App\Filter\DoctrineFilter\ActivityYearFilter;
use App\Filter\DoctrineFilter\DateTimeFilter;
use App\Service\Constraint\ActivityYearConstraint;
use App\Service\Constraint\DateTimeConstraint;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * Classe DoctrineFilterListener qui permet d'assurer l'injection de dépendance pour le SQL Filter
 */
class DoctrineFilterListener
{
    public function __construct(
        private EntityManagerInterface $entityManager,
        private DateTimeConstraint $dateTimeConstraint,
        private ActivityYearConstraint $activityYearConstraint,
        private Security $security,
        private RequestStack $requestStack
    )
    {
    }

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

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

        if($access){
            /** @var DateTimeFilter $dateTimeFilter */
            $dateTimeFilter = $this->entityManager->getFilters()->getFilter('date_time_filter');
            $dateTimeFilter->setParameter('accessId', $access->getId());
            $dateTimeFilter->setParameter('_time_constraint', $this->requestStack->getMainRequest()->get('_time_constraint', true));
            $dateTimeFilter->setDateTimeConstraint($this->dateTimeConstraint);

            /** @var ActivityYearFilter $activityYearFilter */
            $activityYearFilter = $this->entityManager->getFilters()->getFilter('activity_year_filter');
            $activityYearFilter->setParameter('accessId', $access->getId());
            $activityYearFilter->setParameter('_time_constraint', $this->requestStack->getMainRequest()->get('_time_constraint', true));
            $activityYearFilter->setActivityYearConstraint($this->activityYearConstraint);
        }
    }
}