<?php

namespace OSM\Element;

use OSM\Element\Member\Member;

class Element
{
    public ?int $id = null;
    public array $members = [];
    public array $tags = [];

    public static function createFromArray($array)
    {
        assert(is_array($array));

        $hasType = isset($array['type']);
        assert($hasType);

        $className = __NAMESPACE__.'\\'.ucfirst($array['type']);
        $hasClass = class_exists($className);

        $instance = new $className();

        $hasId = isset($array['id']);
        assert($hasId);

        $instance->id = (int) $array['id'];

        $hasMembers = isset($array['members']);
        if ($hasMembers) {
            $items = $array['members'];
            foreach ($items as $item) {
                $member = Member::createFromArray($item);
                $instance->members[] = $member;
            }
        }

        $hasTags = isset($array['tags']);
        if ($hasTags) {
            $items = $array['tags'];
            foreach ($items as $itemKey => $itemValue) {
                $tag = Tag::createFromValues($itemKey, $itemValue);
                $instance->tags[] = $tag;
            }
        }

        $instance->completeFromArray($array);

        return $instance;
    }

    public function completeFromArray(array $array): static
    {
        return $this;
    }

    public function getTagValue(string $key): ?string
    {
        $foundTags = array_filter($this->tags, function ($tag) use ($key) {
            return $tag->key === $key;
        });

        if (1 !== count($foundTags)) {
            return null;
        }

        $tag = reset($foundTags);

        return $tag->value;
    }

    public function asDOMElement(\DOMDocument $document): \DOMElement {
        $reflect = new \ReflectionClass(get_called_class());
        $name = strtolower($reflect->getShortName());
        
        $xml = $document->createElement($name);

        $xml->setAttribute('id', $this->id);
        $xml->setAttribute('visible', 'true');

        foreach ($this->tags as $tag) {
            $tagElement = $document->createElement('tag');
            $tagElement->setAttribute('k', $tag->key);
            $tagElement->setAttribute('v', $tag->value);
            $xml->appendChild($tagElement);
        } 

        return $xml;
    }
}
