<?php

namespace OSM\Element;

use OSM\Element\Member\Member;
use OSM\Element\Tag;

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 (count($foundTags) !== 1) {
            return null;
        }

        $tag = reset($foundTags);
        return $tag->value;
    }
}
