<?php

declare(strict_types=1);

namespace PpPhp\Core\Platform\Metadata\Collections;

use ArrayIterator;
use Countable;
use IteratorAggregate;
use Traversable;
use PpPhp\Core\Platform\Metadata\ValueObjects\PlatformTag;

final class PlatformTagCollection implements IteratorAggregate, Countable
{
    /** @var PlatformTag[] */
    private array $tags = [];

    public function add(PlatformTag $tag): self
    {
        foreach ($this->tags as $existing) {
            if (strcasecmp($existing->name(), $tag->name()) === 0) {
                return $this;
            }
        }

        $this->tags[] = $tag;
        return $this;
    }

    public function contains(string $name): bool
    {
        foreach ($this->tags as $tag) {
            if (strcasecmp($tag->name(), $name) === 0) {
                return true;
            }
        }
        return false;
    }

    /** @return PlatformTag[] */
    public function all(): array
    {
        return $this->tags;
    }

    public function toArray(): array
    {
        return array_map(static fn(PlatformTag $tag): array => $tag->toArray(), $this->tags);
    }

    public function getIterator(): Traversable
    {
        return new ArrayIterator($this->tags);
    }

    public function count(): int
    {
        return count($this->tags);
    }
}
