<?php

namespace RosreestrGeomToWKT;

use RosreestrGeomToWKT\WktUtilites;

class Contours
{
    /**
    * @var object
    */
    private $ut;

    /**
    * @var array
    */
    private $contours;

    /**
    * @var string
    */
    private $entitySpatials;
    
    /**
    * @var string
    */
    public $contoursData;
    
    /**
    * @param array
    */
    public function __construct(array $entitySpatials)
    {
        $this->entitySpatials = $entitySpatials;
        $this->ut = new WktUtilites();
        $this->contoursData = $this->getContoursData();
    }

    /**
    * @return string
    */
    private function getContoursData(): string
    {
        if ($this->ut::validateArray($this->entitySpatials)) {
            $diffContourTypes = [];
            $spatialsCnt = count($this->entitySpatials);

            foreach ($this->entitySpatials as $entitySpatial) {
                $diffContourTypes[] = $entitySpatial->entitySpatialData['type'];
            }
            $diffContourTypes = array_unique($diffContourTypes);

            if ($spatialsCnt === 1) {
                return $diffContourTypes[0] . $this->entitySpatials[0]->entitySpatialData['coordinates'];
            } else {
                if (count($diffContourTypes) === 1) {
                    $wktString = 'MULTI' . $diffContourTypes[0] . '(';
                    foreach ($this->entitySpatials as $esEl) {
                        $wktString .= $esEl->entitySpatialData['coordinates'] . ', ';
                    }
                    $wktString = rtrim($wktString, ', ') . ')';
                    return $wktString;
                } else {
                    $wktString = 'GEOMETRYCOLLECTION(';
                    foreach ($this->entitySpatials as $esEl) {
                        $wktString .= $esEl->entitySpatialData['type'] . $esEl->entitySpatialData['coordinates'] . ', ';
                    }
                    $wktString = rtrim($wktString, ', ') . ')';
                    return $wktString;
                }
            }
        } else {
            throw new \Exception('Entity spatials elements are not found');
        }
    }
}