<?php


namespace Webapp\Core\EventSubscriber;


use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Webapp\Core\Entity\Project;
use Webapp\Core\Entity\StateCode;
use Webapp\Core\Enumeration\ExperimentStateEnum;

class ProjectCreateEventSubscriber implements EventSubscriberInterface
{

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

    public function onProjectCreate(ViewEvent $event): void
    {
        $project = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();
        if (!$project instanceof Project || Request::METHOD_POST !== $method) {
            return;
        }
        /** @var StateCode $stateCode */
        foreach ($project->getPlatform()->getSite()->getStateCodes() as $stateCode) {
            if($stateCode->isPermanent()){
                $project->addStateCode((new StateCode())
                    ->setCode($stateCode->getCode())
                    ->setMeaning($stateCode->getMeaning())
                    ->setTitle($stateCode->getTitle())
                    ->setSpreading($stateCode->getSpreading())
                    ->setColor($stateCode->getColor())
                    ->setPermanent(true));
            }
        }
        foreach ($project->getExperiments() as $experiment){
            if($experiment->getState() < ExperimentStateEnum::LOCKED){
                $experiment->setState(ExperimentStateEnum::LOCKED);
            }
        }
    }
}
