<?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 katastrálního území.
 */
class CadastralArea extends AbstractConverter implements ConverterInterface
{
    /**
     * Nastavuje konfiguraci třídy.
     *
     * @param PointCoordinatesConverter $coordinateConverter
     */
    public function __construct(PointCoordinatesConverter $coordinateConverter)
    {
        parent::__construct($coordinateConverter);
        $this->handledTag = 'vf:KatastralniUzemi';
    }

    /**
     * {@inheritdoc}
     */
    public function convert(\XMLReader $document): ResultInterface
    {
        $element = $this->getNextElement($document);

        if ($element instanceof \XMLReader && $element->name === $this->handledTag) {
            // pokud jsme narazili na tag ku, který obsahuje další ku, zpracujeme to a tuhle přeskočíme
            $this->getNextElement($document);
        }
        $data = ['stav' => 1];
        do {
            switch ($document->name) {
                case 'kui:Kod':
                    $data['ku_kod'] = (int) $document->readString();

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

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

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

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

                    break;
            }
        } while ($this->getNextElement($document));

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

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