<?php


namespace Shared\Authentication\EventSubscriber;


use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\EventListener\EventPriorities;
use Doctrine\ORM\EntityManagerInterface;
use Gedmo\SoftDeleteable\SoftDeleteableListener;
use Shared\Authentication\Entity\Site;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class OnDeleteSiteEventSubscriber implements EventSubscriberInterface
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    private IriConverterInterface $iriConverter;

    public function __construct(EntityManagerInterface $em, IriConverterInterface $iriConverter)
    {
        $this->em = $em;
        $this->iriConverter = $iriConverter;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => ['deleteSite', EventPriorities::PRE_WRITE],
        ];
    }

    public function deleteSite(RequestEvent $event): void
    {
        $method = $event->getRequest()->getMethod();
        $site = $event->getControllerResult();
        if (!$site instanceof Site || Request::METHOD_DELETE !== $method ) {
            return;
        }
        if($site->isDeleted()){
            foreach ($this->em->getEventManager()->getListeners() as $eventName => $listeners) {
                foreach ($listeners as $listener) {
                    if ($listener instanceof SoftDeleteableListener) {

                        // store the event listener, that gets removed
                        $originalEventListeners[$eventName] = $listener;

                        // remove the SoftDeletableSubscriber event listener
                        $this->em->getEventManager()->removeEventListener($eventName, $listener);
                    }
                }
            }
            $entities = [
                ...$site->getExperiments()->toArray(),
                ...$site->getFactors()->toArray(),
                ...$site->getUserRoles()->toArray(),
                ...$site->getPlatforms()->toArray(),
                ...$site->getSimpleVariables()->toArray(),
                ...$site->getGeneratorVariables()->toArray(),
                ...$site->getProtocols()->toArray(),
                ...$site->getValueLists()->toArray(),
                ...$site->getDevices()->toArray(),
                ...$site->getOezNatures()->toArray(),
                ...$site->getStateCodes()->toArray(),
                ...$site->getUserGroups()->toArray(),
                ...$site->getParsingJobs()->toArray(),
            ];
            foreach ($entities as $entity){
                $this->em->remove($entity);
            }
        }
    }
}
