<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Manifest;

final class ManifestCollection
{
    /** @var array<string, ManifestRecord> */
    private array $items = [];

    public function add(ManifestRecord $manifest): void
    {
        $this->items[$manifest->type() . ':' . $manifest->id()] = $manifest;
    }

    public function has(string $type, string $id): bool
    {
        return isset($this->items[$type . ':' . $id]);
    }

    public function get(string $type, string $id): ?ManifestRecord
    {
        return $this->items[$type . ':' . $id] ?? null;
    }

    public function getById(string $id): ?ManifestRecord
    {
        foreach ($this->items as $manifest) {
            if ($manifest->id() === $id) {
                return $manifest;
            }
        }

        return null;
    }

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

    /** @return ManifestRecord[] */
    public function byType(string $type): array
    {
        return array_values(array_filter(
            $this->items,
            static fn (ManifestRecord $manifest): bool => $manifest->type() === $type
        ));
    }

    /** @return ManifestRecord[] */
    public function enabled(): array
    {
        return array_values(array_filter(
            $this->items,
            static fn (ManifestRecord $manifest): bool => $manifest->enabled()
        ));
    }

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

    public function types(): array
    {
        $types = [];

        foreach ($this->items as $manifest) {
            $types[$manifest->type()] = true;
        }

        return array_keys($types);
    }

    public function toArray(): array
    {
        return array_map(static fn (ManifestRecord $manifest): array => $manifest->toArray(), $this->all());
    }
}
