<?php

/*
 * @author TRYDEA - 2024
 */

namespace Webapp\FileManagement\Service\XmlUtils\Normalizer\Webapp;

use Doctrine\Common\Collections\Collection;
use Webapp\Core\Entity\PathBase;
use Webapp\Core\Entity\PathLevelAlgorithm;
use Webapp\FileManagement\Dto\Webapp\CheminementCalculeDto;
use Webapp\FileManagement\Service\XmlUtils\Normalizer\AbstractXmlNormalizer;
use Webapp\FileManagement\Service\XmlUtils\Normalizer\XmlImportConfig;

/**
 * @template-extends AbstractXmlNormalizer<PathBase, PathBaseXmlDto>
 *
 * @psalm-type PathBaseXmlDto = array{
 *      "@name": ?string,
 *      cheminementCalcules: ?CheminementCalculeDto,
 *      cheminements: Collection<int, PathLevelAlgorithm>
 * }
 */
class PathBaseNormalizer extends AbstractXmlNormalizer
{
    protected const ATTR_NAME = '@name';
    protected const TAG_CHEMINEMENT_CALCULES = 'cheminementCalcules';
    protected const TAG_CHEMINEMENTS = 'cheminements';

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

    protected function extractData($object, array $context): array
    {
        throw new \LogicException('Method not implemented');
    }

    protected function getImportDataConfig(array $context): array
    {
        return [
            self::ATTR_NAME => 'string',
            self::TAG_CHEMINEMENT_CALCULES => XmlImportConfig::value(CheminementCalculeDto::class),
            self::TAG_CHEMINEMENTS => XmlImportConfig::collection(PathLevelAlgorithm::class),
        ];
    }

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

    protected function completeImportedObject($object, $data, ?string $format, array $context): PathBase
    {
        /** @var CheminementCalculeDto $cheminementCalcule */
        $cheminementCalcule = $data[self::TAG_CHEMINEMENT_CALCULES] ?? new CheminementCalculeDto();

        $object
            ->setName($data[self::ATTR_NAME])
            ->setAskWhenEntering('sortie' === $cheminementCalcule->declenchement)
            ->setOrderedIris($cheminementCalcule->objects ?? [])
            ->setSelectedIris($cheminementCalcule->objects ?? [])
            ->setPathLevelAlgorithms($data[self::TAG_CHEMINEMENTS]);

        return $object;
    }
}
