<?php

/*
 * @author TRYDEA - 2024
 */

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

use Doctrine\Common\Collections\Collection;
use Webapp\Core\Entity\ValueList;
use Webapp\Core\Entity\ValueListItem;
use Webapp\FileManagement\Entity\RequestFile;
use Webapp\FileManagement\Exception\ParsingException;
use Webapp\FileManagement\Service\XmlUtils\Normalizer\AbstractXmlNormalizer;
use Webapp\FileManagement\Service\XmlUtils\Normalizer\XmlImportConfig;

/**
 * @template-extends AbstractXmlNormalizer<ValueList, ValueListXmlDto>
 *
 * @psalm-type ValueListXmlDto = array{
 *      "@nom": string,
 *      valeurs: Collection<int, ValueListItem>
 * }
 */
class ValueListNormalizer extends AbstractXmlNormalizer
{
    protected const ATTR_NOM = '@nom';
    protected const TAG_VALEURS = 'valeurs';

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

    protected function getImportDataConfig(array $context): array
    {
        return [
            self::ATTR_NOM => 'string',
            self::TAG_VALEURS => XmlImportConfig::collection(ValueListItem::class),
        ];
    }

    protected function validateImportData($data, array $context): void
    {
        if (!isset($data[self::ATTR_NOM])) {
            throw new ParsingException('', RequestFile::ERROR_VALUE_HINT_LIST_INFO_MISSING);
        }
    }

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

    protected function completeImportedObject($object, $data, ?string $format, array $context): ValueList
    {
        $object
            ->setName($data[self::ATTR_NOM])
            ->setValues($data[self::TAG_VALEURS]);

        return $object;
    }

    protected function extractData($object, array $context): array
    {
        return [
            self::ATTR_NOM => $object->getName(),
            self::TAG_VALEURS => $object->getValues()->getValues(),
        ];
    }
}
