<?php

namespace Dalten\RuianToUir\Converter\Field;

use proj4php\Proj;
use proj4php\Proj4php;

readonly class PointCoordinatesConverter
{
    public function __construct(
        private Proj4php $converter,
        private Proj $sourceProjection,
        private Proj $targetProjection)
    {
    }

    public function convertCoords(string $ruianCoordinates): string
    {
        $source = new \proj4php\Point($ruianCoordinates, null, null, $this->sourceProjection);
        $result = $this->converter->transform($this->targetProjection, $source);
        if (!$result instanceof \proj4php\Point) {
            throw new \RuntimeException('Unable to transform coordinates (unexpected result type)');
        }

        /** @var array{0: float, 1: float, 2: float} $coords */
        $coords = $result->toArray();

        // EPSG:5514 má přehozené osy souřadnic, ale je nutné je prohodit až po transformaci na GPS
        return \sprintf('%f %f', $coords[1], $coords[0]);
    }
}
