<?php

namespace Dalten\RuianToUir\Converter;

use Dalten\RuianToUir\Converter\Exception\InvalidRuianDataException;
use Dalten\RuianToUir\Converter\Exception\UnknownParentDataTypeException;
use Dalten\RuianToUir\Converter\Field\PointCoordinatesConverter;
use Dalten\RuianToUir\Converter\Result\RemoveRecord;
use Dalten\RuianToUir\Converter\Result\ResultInterface;

class RemovedItem extends AbstractConverter implements ConverterInterface
{
    /**
     * @param array<string, string> $ruianAddressPartTypeMap
     */
    public function __construct(
        PointCoordinatesConverter $coordinateConverter,
        private readonly array $ruianAddressPartTypeMap)
    {
        parent::__construct($coordinateConverter);
        $this->handledTag = 'vf:ZaniklyPrvek';
    }

    /**
     * Převádí informace o smazaném prvku do standardizovaného formátu.
     *
     * @param \XMLReader $document instance readeru s kurzorem na testovaném prvku
     *
     * @return ResultInterface pole s daty ve formátu UIR
     */
    public function convert(\XMLReader $document): ResultInterface
    {
        // <vf:ZaniklyPrvek><vf:TypPrvkuKod>SO</vf:TypPrvkuKod><vf:PrvekId>43628028</vf:PrvekId><vf:IdTransakce>1732987</vf:IdTransakce></vf:ZaniklyPrvek>
        $data = [];

        while ($this->getNextElement($document)) {
            switch ($document->name) {
                case 'vf:TypPrvkuKod':
                    $type = $document->readString();
                    $data['parent_converter'] = $this->ruianAddressPartTypeMap[$type] ?? null;

                    break;
                case 'vf:PrvekId':
                    $data['identifier'] = (int) $document->readString();

                    break;
                default:
                    $this->skipToElementEnd($document);

                    break;
            }
        }

        if (empty($data['parent_converter'])) {
            throw UnknownParentDataTypeException::becauseOfUnknownRemovedItemType($type ?? '?');
        }

        if (empty($data['identifier'])) {
            throw InvalidRuianDataException::becauseRequiredAttributeIsMissing($this->getName(), 'vf:PrvekId');
        }

        return new RemoveRecord($data['parent_converter'], $data['identifier']);
    }
}
