<?php

namespace App\Twig\Components;

use App\Search\Action\Command\GetMediaInfoCommand;
use App\Search\Action\Handler\GetMediaInfoHandler;
use App\Search\TvEpisodePaginator;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent]
final class  TvEpisodeList
{
    use DefaultActionTrait;
    use PaginateTrait;

    #[LiveProp(writable: true)]
    public string $title = "";

    #[LiveProp(writable: true)]
    public string $imdbId = "";

    #[LiveProp(writable: true)]
    public string $tmdbId = "";

    #[LiveProp(writable: true)]
    public int $season = 1;

    #[LiveProp(writable: true)]
    public int $reloadCount = 0;

    #[LiveProp(writable: true)]
    public ?int $episodeNumber = null;

    public function __construct(
        private GetMediaInfoHandler $getMediaInfoHandler,
    ) {}

    public function getEpisodes()
    {
        $results = $this->getMediaInfoHandler->handle(new GetMediaInfoCommand($this->imdbId, "tvshows", $this->season));

        if (null !== $this->episodeNumber) {
            $this->pageNumber = ceil($this->episodeNumber / $this->perPage);
            $this->episodeNumber = null;
        }

        $this->reloadCount++;
        return new TvEpisodePaginator()->paginate($results, $this->pageNumber, $this->perPage);
    }

    public function setPage(int $page)
    {
        $this->pageNumber = $page;
    }
}
