<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Worker\Monitoring;

final class WorkerHeartbeatCollection
{
    private array $heartbeats = [];

    public static function fromArray(array $items): self
    {
        $collection = new self();
        foreach ($items as $item) {
            if (is_array($item)) {
                $collection->record(WorkerHeartbeat::fromArray($item));
            }
        }
        return $collection;
    }

    public function record(WorkerHeartbeat $heartbeat): void
    {
        $this->heartbeats[$heartbeat->workerId()] = $heartbeat;
    }

    public function get(string $workerId): ?WorkerHeartbeat
    {
        return $this->heartbeats[$workerId] ?? null;
    }

    public function all(): array
    {
        return array_values($this->heartbeats);
    }

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

    public function clear(): void
    {
        $this->heartbeats = [];
    }

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