<?php

/*
 * @author TRYDEA - 2024
 */

namespace Webapp\FileManagement\Service;

use Mobile\Project\Entity\DataEntryProject;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
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\Dto\Mobile\XmlWithFiles;
use Webapp\FileManagement\Service\XmlUtils\Normalizer\AbstractXmlNormalizer;
use Webapp\FileManagement\Service\XmlUtils\WriterHelper;

final class MobileXmlWriterService
{
    private SerializerInterface $serializer;

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

    public function generateDataEntry(DataEntryProject $dataEntryProject): XmlWithFiles
    {
        return $this->serialize(new ReturnFileDto($dataEntryProject));
    }

    public function generateDataEntryProject(DataEntryProject $project): XmlWithFiles
    {
        return $this->serialize(new ProjectDto($project));
    }

    /**
     * @param ProjectDto|ReturnFileDto $dto
     */
    private function serialize($dto): XmlWithFiles
    {
        $writerHelper = new WriterHelper(null);
        $xml = $this->serializer->serialize($dto, 'xml', [
            AbstractObjectNormalizer::SKIP_NULL_VALUES => true,
            XmlEncoder::REMOVE_EMPTY_TAGS => true,
            XmlEncoder::ENCODING => 'UTF-8',
            XmlEncoder::FORMAT_OUTPUT => true,
            XmlEncoder::ROOT_NODE_NAME => 'xmi:XMI',
            XmlEncoder::VERSION => '1.0',
            DateTimeNormalizer::FORMAT_KEY => \DateTimeInterface::RFC3339_EXTENDED,
            AbstractXmlNormalizer::EXPORT_XML => true,
            AbstractXmlNormalizer::WRITER_HELPER => $writerHelper,
        ]);

        return new XmlWithFiles(
            $xml,
            array_merge($writerHelper->getAnnotationFiles(), $writerHelper->getMarkFiles())
        );
    }
}
