<?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 parcely.
 */
class Plot extends AbstractConverter implements ConverterInterface
{
    /**
     * Nastavuje konfiguraci třídy.
     *
     * @param PointCoordinatesConverter $coordinateConverter
     */
    public function __construct(PointCoordinatesConverter $coordinateConverter)
    {
        parent::__construct($coordinateConverter);
        $this->handledTag = 'vf:Parcela';
    }

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

                    break;
                case 'pai:KmenoveCislo':
                    $data['kmenove_cislo'] = (int) $document->readString();

                    break;
                case 'pai:PododdeleniCisla':
                    $data['pododdeleni_cisla'] = (int) $document->readString();

                    break;
                case 'pai:DruhCislovaniKod':
                    $data['druh_cislovani'] = (int) $document->readString();

                    break;
                case 'pai:DruhPozemkuKod':
                    $data['druh_pozemku'] = (int) $document->readString();

                    break;
                case 'pai:VymeraParcely':
                    $data['vymera_parcely'] = (int) $document->readString();

                    break;
                case 'pai:KatastralniUzemi':
                    if (!$document->isEmptyElement) {
                        $this->getNextElement($document);
                        if ('kui:Kod' === $document->name) {
                            $data['ku_kod'] = (int) $document->readString();
                        }
                    }

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

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

                    break;
            }
        }

        if (empty($data['parcela_kod'])) {
            throw InvalidRuianDataException::becauseRequiredAttributeIsMissing($this->getName(), 'pai:Id');
        }

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