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

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

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

                    break;
                case 'oki:NutsLau':
                    $data['nuts4'] = (string) $document->readString();

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

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

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

                    break;
            }
        }

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

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