<?php

namespace App\Monitor\Framework\Controller;

use Aimeos\Map;
use App\Base\Service\Broadcaster;
use App\Monitor\Action\Handler\AddMonitorHandler;
use App\Monitor\Action\Handler\DeleteMonitorHandler;
use App\Monitor\Action\Input\AddMonitorInput;
use App\Monitor\Action\Input\DeleteMonitorInput;
use App\Monitor\Framework\Repository\MonitorRepository;
use App\Monitor\Framework\Scheduler\MonitorDispatcher;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Routing\Attribute\Route;

class ApiController extends AbstractController
{
    public function __construct(
        private readonly Broadcaster $broadcaster,
    ) {}

    #[Route('/api/monitor', name: 'api_monitor', methods: ['POST'])]
    public function addMonitor(
        AddMonitorInput $input,
        AddMonitorHandler $handler,
        HubInterface $hub,
    ) {
        $command = $input->toCommand();
        $command->userId = $this->getUser()->getId();
        $response = $handler->handle($command);

        $this->broadcaster->alert(
            title: 'Success',
            message: "New monitor added for {$input->title}",
        );

        return $this->json([
            'status' => 200,
            'message' => $response
        ]);
    }

    #[Route('/api/monitor/{monitorId}', name: 'api_monitor_delete', methods: ['DELETE'])]
    public function deleteMonitor(
        DeleteMonitorInput $input,
        DeleteMonitorHandler $handler,
    ) {
        $response = $handler->handle($input->toCommand());

        return $this->json([
            'status' => 200,
            'message' => $response
        ]);
    }

    #[Route('/api/monitor/dispatch', name: 'api_monitor_dispatch', methods: ['GET'])]
    public function dispatch(MonitorDispatcher $dispatcher, Broadcaster $broadcaster): Response
    {
        $dispatcher();

        $broadcaster->alert('Success', 'The monitor job has been dispatched.');

        return $this->json([
            'status' => 200,
            'message' => 'Manually dispatched MonitorDispatcher'
        ]);
    }

    #[Route('/api/monitor/upcoming-episodes', name: 'api.monitor.upcoming-episodes', methods: ['GET'])]
    public function upcomingEpisodes(MonitorRepository $repository): Response
    {
        $colors = [
            'blue' => '#007bff',
            'indigo' => '#6610f2',
            'purple' => '#6f42c1',
            'pink' => '#e83e8c',
            'red' => '#dc3545',
            'orange' => '#fd7e14',
            'yellow' => '#ffc107',
            'green' => '#28a745',
            'teal' => '#20c997',
            'cyan' => '#17a2b8',
        ];

        $eventColors = [];
        $monitors = $repository->whereAirDateNotNull();
        $monitors = Map::from($monitors)->map(function ($monitor) use (&$eventColors, $colors) {
            if (!array_key_exists($monitor->getImdbId(), $eventColors)) {
                $eventColors[$monitor->getImdbId()] = $colors[array_rand($colors)];
            }
            return [
                'id' => $monitor->getId(),
                'title' => $monitor->getTitle() . ' (S' . str_pad($monitor->getSeason(), 2, '0', STR_PAD_LEFT) . 'E' . str_pad($monitor->getEpisode(), 2, '0', STR_PAD_LEFT) . ')',
                'start' => $monitor->getAirDate()->format('Y-m-d H:i:s'),
                'groupId' => $monitor->getImdbId(),
                'allDay' => true,
                'backgroundColor' => $eventColors[$monitor->getImdbId()],
                'borderColor' => $eventColors[$monitor->getImdbId()],
                'attachment' => $monitor->getPoster(),
            ];
        });

        return $this->json([
            'status' => 200,
            'data' => [
                'episodes' => $monitors->toArray(),
            ]
        ]);
    }
}
