<?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 obce.
 */
class Municipality extends AbstractConverter implements ConverterInterface
{
    public function __construct(PointCoordinatesConverter $coordinateConverter)
    {
        parent::__construct($coordinateConverter);
        $this->handledTag = 'vf:Obec';
    }

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

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

                    break;
                case 'obi:StatusKod':
                    $data['typ_obce'] = (int) $document->readString();

                    break;
                case 'obi:NutsLau':
                    $data['nuts5'] = $document->readString();

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

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

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

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

                    break;
            }
        }

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

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