<?php

namespace App\Service;

use App\Entity\Slot;
use App\Entity\Space;
use App\Entity\Period;

class SlotFinder
{
    /** @var array<string, Slot> */
    private array $index = [];

    public function __construct(iterable $slots)
    {
        foreach ($slots as $slot) {
            $this->index[$this->makeKey($slot->getStartOn(), $slot->getSpace()->getId(), $slot->getPeriod()->getId())] = $slot;
        }
    }

    public function find(\DateTimeInterface $dateRef, Space $space, Period $period): ?Slot
    {
        $key = $this->makeKey($dateRef, $space->getId(), $period->getId());
        $found = $this->index[$key] ?? null;
        return $found;
    }

    private function makeKey(\DateTimeInterface $startOn, $spaceId, $periodId): string
    {
        return $startOn->format('Y-m-d H:i:s') . '|' . $spaceId . '|' .$periodId;
    }
}
