<?php

namespace OSM;

use OSM\Element\Element;

class OSM
{
    public array $elements = [];

    public static function createFromJson($json)
    {
        $array = json_decode($json, true);

        return self::createFromArray($array);
    }

    public static function createFromArray($array)
    {
        $instance = new self();

        $items = $array['elements'];
        foreach ($items as $item) {
            $element = Element::createFromArray($item);
            $instance->elements[] = $element;
        }

        return $instance;
    }

    public function __toString() {
        $document = new \DOMDocument('1.0', 'UTF-8');

        $osm = $document->createElement('osm');
        $osm->setAttribute('version', '0.6');

        foreach ($this->elements as $element) {
            $osm->appendChild($element->asDOMElement($document));
        }

        $document->appendChild($osm);

        return $document->saveXML();
    }
}
