<?php

namespace Webapp\Core\ApiOperation;

use ApiPlatform\Core\Api\IriConverterInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
use Webapp\Core\Entity\CloneExperiment\CloneExperiment;
use Webapp\Core\Enumeration\ExperimentStateEnum;
use Webapp\Core\Service\CloneService;

/**
 * Class CloneExperimentOperation.
 */
final class CloneExperimentOperation
{
    private CloneService $cloneService;

    private EntityManagerInterface $entityManager;

    private IriConverterInterface $iriConverter;

    private Security $security;

    public function __construct(EntityManagerInterface $entityManager, CloneService $cloneService, IriConverterInterface $iriConverter, Security $security)
    {
        $this->cloneService = $cloneService;
        $this->entityManager = $entityManager;
        $this->iriConverter = $iriConverter;
        $this->security = $security;
    }

    /**
     * @param Request $request
     * @param CloneExperiment $data
     * @return CloneExperiment
     */
    public function __invoke(Request $request, $data)
    {
        $site = $data->getExperiment()->getSite() ?? $data->getExperiment()->getPlatform()->getSite();
        $iriMap = [];
        foreach ($site->getOezNatures() as $oezNature) {
            $iriMap[$this->iriConverter->getIriFromItem($oezNature)] = $oezNature;
        }
        $res = $this->cloneService->cloneExperiment($data->getExperiment(), $iriMap)
            ->setOwner($this->security->getUser())
            ->setValidated(null)
            ->setState(ExperimentStateEnum::CREATED)
            ->setName($data->getNewName())
            ->setSite($site);

        $this->entityManager->persist($res);
        $this->entityManager->flush();
        return $data->setId(0)->setResult($res);
    }



}
