<?php

namespace Webapp\Core\EventSubscriber;

use ApiPlatform\Core\EventListener\EventPriorities;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\Types\This;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use Webapp\Core\Entity\CloneSite\CloneSite;
use Webapp\Core\Worker\SiteWorker;

/**
 * Class OnSiteCloneSubscriber.
 */
final class OnSiteCloneSubscriber implements EventSubscriberInterface
{
    private SiteWorker $siteWorker;

    private Security $security;

    private EntityManagerInterface $entityManager;

    public function __construct(SiteWorker $siteWorker, Security $security, EntityManagerInterface $entityManager)
    {
        $this->siteWorker = $siteWorker;
        $this->security = $security;
        $this->entityManager = $entityManager;
    }

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

    public function startCloning(ViewEvent $event)
    {
        $result = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        if (!$result instanceof CloneSite || Request::METHOD_POST !== $method) {
            return;
        }
        $result->setAdmin($this->security->getUser());
        $this->entityManager->flush();
        $this->siteWorker->later()->cloneSite($result->getId());

    }
}
