<?php


namespace AutoAdmin\Bundle\Content\EventListener;


use AutoAdmin\Bundle\Content\Context\SiteContext;
use AutoAdmin\Bundle\Content\Site\SiteMatcher;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpKernel\Event\RequestEvent;

class SiteRequestListener
{
    private SiteContext $context;
    private ManagerRegistry $doctrine;
    private SiteMatcher $matcher;

    public function __construct(SiteContext $context, ManagerRegistry $doctrine, SiteMatcher $matcher)
    {
        $this->context = $context;
        $this->doctrine = $doctrine;
        $this->matcher = $matcher;
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $request = $event->getRequest();
        if ($request->attributes->get('_controller') === 'error_controller') {
            return;
        }

        if ($this->context->getSite() === null && $this->context->getLocale() === null) {
            $this->matcher->matchSite($request, $this->context);
        }
    }

    public function onKernelException(RequestEvent $event): void
    {
        $request = $event->getRequest();
        if ($request->attributes->get('_controller') === 'error_controller') {
            return;
        }
        if ($this->context->getSite() === null && $this->context->getLocale() === null) {
            $this->matcher->matchSite($request, $this->context);
        }
    }
}