<?php

namespace App\Download\Action\Handler;

use Aimeos\Map;
use App\Monitor\Framework\Entity\Monitor;
use App\Monitor\Framework\Repository\MonitorRepository;
use App\Tmdb\Dto\TmdbEpisodeDto;
use App\Tmdb\TmdbClient;
use Carbon\Carbon;
use DateTimeImmutable;
use Psr\Log\LoggerInterface;

trait MonitorHandlerTrait
{
    private MonitorRepository $monitorRepository;
    private LoggerInterface $logger;
    private TmdbClient $tmdb;

    private function episodeReleasedAfterMonitorCreated(
        string|DateTimeImmutable $monitorStartDate,
        TmdbEpisodeDto $episodeInShow
    ): bool {
        $monitorStartDate = Carbon::parse($monitorStartDate)->setTime(0, 0);
        $episodeAirDate = Carbon::parse($episodeInShow->airDate);
        return $episodeAirDate >= $monitorStartDate;
    }

    private function episodeExists(TmdbEpisodeDto $episodeInShow, Map $downloadedEpisodes): bool
    {
        return $downloadedEpisodes->filter(
                fn(object $episode) => $episode->episode === $episodeInShow->episodeNumber
                    && $episode->season === $episodeInShow->seasonNumber
            )->count() > 0;
    }

    private function monitorExists(Monitor $monitor, TmdbEpisodeDto $episode): bool
    {
        return $this->monitorRepository->findOneBy([
                'imdbId' => $monitor->getImdbId(),
                'title' => $monitor->getTitle(),
                'monitorType' => 'tvepisode',
                'season' => $episode->seasonNumber,
                'episode' => $episode->episodeNumber,
                'status' => ['New', 'Active', 'In Progress']
            ]) !== null;
    }

    private function refreshData(Monitor $monitor)
    {
        if (null === $monitor->getPoster()) {
            $this->logger->info('> [MonitorTvShowHandler] Refreshing poster for "' . $monitor->getTitle() . '"');
            $poster = $this->tmdb->tvshowDetails($monitor->getImdbId())->poster;
            if (null !== $poster && "" !== $poster) {
                $monitor->setPoster($poster);
            }
        }
    }
}
