<?php

namespace App\MessageHandler;

use App\Entity\UserDownloader;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpFoundation\File\File;

#[AsMessageHandler]
class DownloaderVideoHandler
{

    private string $path;

    public function __construct(
        private EntityManagerInterface $entityManager,
        private KernelInterface $kernel
    ) {
        $this->path = $this->kernel->getProjectDir() . '/public/downloader/user/';
    }

    public function __invoke(UserDownloader $userDownloader)
    {
        $url = $userDownloader->getUrl();
        $user = $userDownloader->getUser();

        if ($user && !$this->entityManager->contains($user)) {
            $user = $this->entityManager->find(\App\Entity\User::class, $user->getId());
            $userDownloader->setUser($user);
        }

        $pathDownload = $this->path . $user->getId();
        if (!is_dir($pathDownload)) {
            mkdir($pathDownload, 0777, true);
        }

        $pathDownload .= "/".$userDownloader->getNameFile();

        // 2. Lancer le vrai téléchargement
        // Assurez-vous que le dossier de destination existe et est accessible en écriture

        $downloadProcess = new Process(['yt-dlp', '-o', $pathDownload, $url]);
        $downloadProcess->setTimeout(3600); // Augmenter le timeout pour les grosses vidéos
        $downloadProcess->run();

        if (!$downloadProcess->isSuccessful()) {
            $processFailedException =  new ProcessFailedException($downloadProcess);
            $errorString = $processFailedException->getMessage();
            $userDownloader->setException($errorString);
        }
        
        // 3. Une fois terminé avec succès, on enregistre en Base de Données
        $userDownloader->setDateEnd(new \DateTime());

        $file = new File($pathDownload);
        $megabytes = round($file->getSize() / 1048576, 2);
        $userDownloader->setSizeFile($megabytes);

        $this->entityManager->persist($userDownloader);
        $this->entityManager->flush();
    }
}
