<?php


namespace Webapp\Core\Dto\Experiment\ExportOpenSilex;


use ApiPlatform\Core\Api\OperationType;
use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
use ApiPlatform\Core\Serializer\AbstractItemNormalizer;
use ApiPlatform\Core\Validator\ValidatorInterface;
use Webapp\Core\Entity\Experiment;
use Webapp\Core\Entity\Factor;
use Webapp\Core\Entity\Modality;

class ExperimentOpenSilexImportTransformer implements DataTransformerInterface
{
    private ValidatorInterface $validator;

    public function __construct(ValidatorInterface $validator)
    {
        $this->validator = $validator;
    }

    /**
     * @param object $object
     * @param string $to
     * @param array $context
     * @return object
     */
    public function transform($object, string $to, array $context = []): object
    {
        /** @var ExperimentExportOpenSilex $object */
        $this->validator->validate($object);

        /** @var Experiment $experiment */
        $experiment = $context[AbstractItemNormalizer::OBJECT_TO_POPULATE];
        $experiment
            ->setOpenSilexInstance($object->getOpenSilexInstance());

        foreach ($experiment->getProtocol()->getFactors()->filter(fn(Factor $f) => !$f->isGermplasm()) as $factor){
            $factorInput = array_values(array_filter($object->getProtocol()->getFactors(), fn(ExperimentExportOpenSilexFactor $factorItem) => $factorItem->getId() === $factor->getId()))[0];
            $factor->getModalities()->map(fn(Modality $modality) => $modality->setOpenSilexUri(array_values(array_filter($factorInput->getModalities(),fn(ExperimentExportOpenSilexModality $item) => $item->getValue()))[0]->getOpenSilexUri()));
        }

        return $experiment;
    }

    public function supportsTransformation($data, string $to, array $context = []): bool
    {
        if ($data instanceof Experiment) {
            return false;
        }
        return Experiment::class === $to &&
            $context['operation_type'] === OperationType::ITEM &&
            $context['item_operation_name'] === 'updateOpenSilexUri' &&
            null !== ($context['input']['class'] ?? null);
    }
}
