<?php

/*
 * @author TRYDEA - 2024
 */

namespace Webapp\FileManagement\Service\XmlUtils\Normalizer;

use Webapp\Core\Entity\Experiment;
use Webapp\Core\Entity\OezNature;
use Webapp\FileManagement\Dto\Webapp\ExperimentDto;

/**
 * @template-extends AbstractRootNormalizer<ExperimentDto, ExperimentDtoXmlDto>
 *
 * @psalm-type ExperimentDtoXmlDto =array{
 *       "adonis.modeleMetier.plateforme:NatureZhe": OezNature[],
 *       "adonis.modeleMetier.plateforme:Dispositif": ?Experiment,
 *  }
 */
class ExperimentDtoNormalizer extends AbstractRootNormalizer
{
    protected const TAG_UTILISATEUR = 'adonis.modeleMetier.utilisateur:Utilisateur';
    protected const TAG_NATURE_ZHE = 'adonis.modeleMetier.plateforme:NatureZhe';
    protected const TAG_DISPOSITIF = 'adonis.modeleMetier.plateforme:Dispositif';

    protected function getClass(): string
    {
        return ExperimentDto::class;
    }

    public function denormalize($data, string $type, ?string $format = null, array $context = []): ExperimentDto
    {
        self::initDenormalizeContext($context);

        return parent::denormalize($data, $type, $format, $context);
    }

    protected function getImportDataConfig(array $context): array
    {
        return [
            self::TAG_NATURE_ZHE => XmlImportConfig::values(OezNature::class, true),
            self::TAG_DISPOSITIF => XmlImportConfig::value(Experiment::class, true),
        ];
    }

    protected function generateImportedObject($data, array $context): ExperimentDto
    {
        return new ExperimentDto();
    }

    protected function completeImportedObject($object, $data, ?string $format, array $context): ExperimentDto
    {
        $object->experiment = $data[self::TAG_DISPOSITIF];
        $object->oezNatures = $data[self::TAG_NATURE_ZHE];

        return $object;
    }

    public function normalize($object, ?string $format = null, array $context = []): array
    {
        self::initNormalizeContext($object->user, $context, 1); // Pass index 0 which correspond to AdonisVersion

        return parent::normalize($object, $format, $context);
    }

    protected function extractData($object, array $context): array
    {
        if (null === $object->experiment) {
            throw new \LogicException('$object->experiment must not be null');
        }

        return array_merge(parent::extractData($object, $context), [
            self::TAG_UTILISATEUR => new XmlExportConfig($object->user, false),
            self::TAG_NATURE_ZHE => new XmlExportConfig($object->oezNatures, false),
            self::TAG_DISPOSITIF => new XmlExportConfig($object->experiment, false),
        ]);
    }
}
