<?php

namespace Dalten\RuianToUir\Converter;

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

/**
 * Převaděč na entitu části obce.
 */
class MunicipalityPart extends AbstractConverter implements ConverterInterface
{
    /**
     * Nastavuje konfiguraci třídy.
     *
     * @param PointCoordinatesConverter $coordinateConverter
     */
    public function __construct(PointCoordinatesConverter $coordinateConverter)
    {
        parent::__construct($coordinateConverter);
        $this->handledTag = 'vf:CastObce';
    }

    /**
     * {@inheritdoc}
     */
    public function convert(\XMLReader $document): ResultInterface
    {
        $data = ['stav' => 1];
        while ($this->getNextElement($document)) {
            switch ($document->name) {
                case 'coi:Kod':
                    $data['cobce_kod'] = (int) $document->readString();

                    break;
                case 'coi:Nazev':
                    $data['zkratka'] = $data['nazev'] = $document->readString();

                    break;
                case 'coi:Obec':
                    if (!$document->isEmptyElement) {
                        $this->getNextElement($document);
                        if ('obi:Kod' === $document->name) {
                            $data['obec_kod'] = (int) $document->readString();
                        }
                    }

                    break;
                case 'coi:Geometrie':
                    if (!$document->isEmptyElement) {
                        $data['geom'] = $this->getGeometryData($document);
                    }

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

                    break;
            }
        }

        if (empty($data['cobce_kod'])) {
            throw InvalidRuianDataException::becauseRequiredAttributeIsMissing($this->getName(), 'coi:Kod');
        }

        return new AddRecord($this->getName(), $data['cobce_kod'], $data);
    }
}
