<?php

declare(strict_types=1);

namespace PpPhp\Core\Assets;

final class AssetCollection
{
    /** @var array<string, Asset> */
    private array $assets = [];

    public function add(Asset $asset): void
    {
        $this->assets[$asset->key()] = $asset;
    }

    public function merge(self $collection): void
    {
        foreach ($collection->all() as $asset) {
            $this->add($asset);
        }
    }

    /** @return Asset[] */
    public function all(): array
    {
        $assets = array_values($this->assets);

        usort(
            $assets,
            static fn(Asset $a, Asset $b): int => $a->priority <=> $b->priority
        );

        return $assets;
    }

    /** @return Asset[] */
    public function byLocation(string $location): array
    {
        return array_values(array_filter(
            $this->all(),
            static fn(Asset $asset): bool => $asset->location === $location
        ));
    }
}
