<?php


namespace Webapp\Core\EventSubscriber;


use ApiPlatform\Core\EventListener\EventPriorities;
use Doctrine\ORM\EntityManagerInterface;
use Shared\RightManagement\Entity\AbstractAdvancedRight;
use Shared\RightManagement\Entity\AdvancedGroupRight;
use Shared\RightManagement\Entity\AdvancedUserRight;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Webapp\Core\Entity\Experiment;

class AdvancedRightEventSubscriber implements EventSubscriberInterface
{
    private EntityManagerInterface $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

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

    public function onLinkDeviceToPlatform(RequestEvent $event): void
    {
        $resource = $event->getRequest()->attributes->get('_api_resource_class');
        if (Experiment::class !== $resource || $event->getRequest()->getMethod() !== Request::METHOD_PATCH) {
            return;
        }
        if(str_ends_with($event->getRequest()->getRequestUri(), "restore")){
            return;
        }

        /** @var Experiment $previous_data */
        $previous_data = $event->getRequest()->attributes->get('previous_data');
        /** @var Experiment $result */
        $result = $event->getRequest()->attributes->get('data');

        if ($previous_data->getPlatform() !== null || $result->getPlatform() === null) {
            return;
        }

        $groupRightRepo = $this->entityManager->getRepository(AdvancedGroupRight::class);
        $userRightRepo = $this->entityManager->getRepository(AdvancedUserRight::class);

        /** @var AdvancedUserRight $item */
        foreach ($userRightRepo->findBy([
            'classIdentifier' => 'webapp_experiment',
            'objectId' => $previous_data->getId(),
        ]) as $item) {
            $item->setClassIdentifier('webapp_platform')
                ->setRight(AbstractAdvancedRight::ADVANCED_RIGHT_VIEW)
                ->setObjectId($result->getPlatform()->getId());
            if ($userRightRepo->find([
                    'userId' => $item->getUserId(),
                    'classIdentifier' => $item->getClassIdentifier(),
                    'objectId' => $item->getObjectId(),
                ]) !== null) {
                $this->entityManager->remove($item);
            }
        }

        /** @var AdvancedGroupRight $item */
        foreach ($groupRightRepo->findBy([
            'classIdentifier' => 'webapp_experiment',
            'objectId' => $previous_data->getId(),
        ]) as $item) {
            $item->setClassIdentifier('webapp_platform')
                ->setRight(AbstractAdvancedRight::ADVANCED_RIGHT_VIEW)
                ->setObjectId($result->getPlatform()->getId());
            if ($groupRightRepo->find([
                    'groupId' => $item->getGroupId(),
                    'classIdentifier' => $item->getClassIdentifier(),
                    'objectId' => $item->getObjectId(),
                ]) !== null) {
                $this->entityManager->remove($item);
            }
        }

        if (
            $result->getPlatform()->getOwner() !== $previous_data->getOwner() &&
            $userRightRepo->find([
                'userId' => $previous_data->getOwner()->getId(),
                'classIdentifier' => 'webapp_platform',
                'objectId' => $result->getPlatform()->getId(),
            ]) === null
        ) {
            $ownerRight = new AdvancedUserRight();
            $ownerRight->setUserId($previous_data->getOwner()->getId())
                ->setRight(AbstractAdvancedRight::ADVANCED_RIGHT_VIEW)
                ->setClassIdentifier('webapp_platform')
                ->setObjectId($result->getPlatform()->getId());
            $this->entityManager->persist($ownerRight);
        }
    }
}
