<?php

/*
 * @author TRYDEA - 2024
 */

namespace Webapp\FileManagement\Service;

use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Webapp\FileManagement\Dto\Mobile\ProjectDto;
use Webapp\FileManagement\Dto\Mobile\ReturnFileDto;
use Webapp\FileManagement\Service\XmlUtils\CustomXmlEncoder;
use Webapp\FileManagement\Service\XmlUtils\Normalizer\AbstractRootNormalizer;
use Webapp\FileManagement\Service\XmlUtils\Normalizer\AbstractXmlNormalizer;
use Webapp\FileManagement\Service\XmlUtils\Normalizer\Mobile\ReturnFileDtoNormalizer;

final class MobileXmlReaderService
{
    private SerializerInterface $serializer;

    public function __construct(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }

    public function readProjectFile(string $xml, ?string $filesPath = null): ProjectDto
    {
        return $this->deserialize($xml, ProjectDto::class, [
            AbstractRootNormalizer::FILES_PATH => $filesPath,
        ]);
    }

    public function readReturnFile(string $xml, string $platformName, string $requestName, ?string $filesPath = null): ReturnFileDto
    {
        return $this->deserialize($xml, ReturnFileDto::class, [
            ReturnFileDtoNormalizer::PLATFORM_NAME => $platformName,
            ReturnFileDtoNormalizer::REQUEST_NAME => $requestName,
            AbstractRootNormalizer::FILES_PATH => $filesPath,
        ]);
    }

    /**
     * @template T
     *
     * @param class-string<T> $dtoClass
     *
     * @return T
     */
    private function deserialize(string $xml, string $dtoClass, array $context = [])
    {
        return $this->serializer->deserialize($xml, $dtoClass, CustomXmlEncoder::FORMAT, array_merge([
            XmlEncoder::AS_COLLECTION => true,
            XmlEncoder::ENCODING => 'UTF-8',
            DateTimeNormalizer::FORMAT_KEY => \DateTimeInterface::RFC3339_EXTENDED,
            AbstractXmlNormalizer::IMPORT_XML => true,
        ], $context));
    }
}
