<?php

namespace App\Monitor\Framework\Controller;

use Aimeos\Map;
use App\Monitor\Framework\Entity\Monitor;
use App\Monitor\Framework\Repository\MonitorRepository;
use App\User\Framework\Entity\User;
use Spatie\IcalendarGenerator\Components\Calendar;
use Spatie\IcalendarGenerator\Components\Event;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

class CalendarController extends AbstractController
{
    #[IsGranted('PUBLIC_ACCESS')]
    #[Route('/monitors/ical/{email:user}/upcoming-episodes.ics', name: 'app.monitors.ical')]
    public function icalAction(MonitorRepository $monitorRepository, User $user)
    {
        if (false === $user->hasICalEnabled()) {
            return new Response('Calendar not found.', 404);
        }

        $calendar = Calendar::create()
             ->name('Upcoming Episodes')
             ->refreshInterval(10);

        $monitors = $monitorRepository->whereAirDateNotNull();
        $calendar->event(Map::from($monitors)->map(function (Monitor $monitor) {
            $event = new Event($monitor->getTitle())
                ->startsAt($monitor->getAirDate())
                ->fullDay();
            if (null !== $monitor->getPoster()) {
                $event->attachment($monitor->getPoster());
            }
            return $event;
        })->toArray());

        return new Response($calendar->get(), 200, [
            'Content-Type' => 'text/calendar',
            'Content-Disposition' => 'inline; filename="upcoming-episodes.ics"',
        ]);
    }
}
