<?php

namespace Webapp\Core\Validator\Project;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Webapp\Core\Entity\Project;
use Webapp\Core\Enumeration\ExperimentStateEnum;

class ProjectPostConstraintValidator extends ConstraintValidator
{
    private EntityManagerInterface $entityManager;

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

    /**
     * @param Project $value
     * @param Constraint $constraint
     */
    public function validate($value, Constraint $constraint)
    {
        $originalExperiment = $this->entityManager->getUnitOfWork()->getOriginalEntityData($value);
        if(count($originalExperiment) !== 0){
            // PATCH case
            return;
        }

        foreach ($value->getExperiments() as $experiment){
            if($experiment->getState() < ExperimentStateEnum::VALIDATED){
                $this->context->buildViolation("Cannot add non locked experiment")->addViolation();
            }
            if(!in_array($experiment, $value->getPlatform()->getExperiments()->toArray(), true)){
                $this->context->buildViolation("Cannot add an experiment that is not in the platform")->addViolation();
            }
        }
    }
}
