<?php

namespace App\Controller;

use App\Entity\Chapter;
use App\Entity\ContentSource;
use App\Entity\Manga;
use App\Message\DownloadChapter;
use App\Repository\ChapterRepository;
use App\Repository\MangaRepository;
use App\Service\ActivityService;
use App\Service\MangadexProvider;
use App\Service\MangaScraperService;
use App\Service\MangaUpdatesMetadataProvider;
use Doctrine\DBAL\Connection;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\String\Slugger\SluggerInterface;

class TestController extends AbstractController
{
    private ImageManager $imageManager;
    public function __construct(
        private string $projectDir,
        private SluggerInterface $slugger,
        private MangaRepository $mangaRepository
    ) {
        $this->imageManager = new ImageManager(new Driver());
    }

    #[Route('/test', name: 'test')]
    public function test(): Response
    {
        $mangas = $this->mangaRepository->findAll();

        $changed = 0;
        foreach ($mangas as $manga) {
            //si getImageUrl() retourne un lien sous la forme d'une URL (https ou http)
            if ($manga->getImageUrl()) {
                $imageUrls = $this->processAndSaveImage($manga->getImageUrl());
                $manga->setThumbnailUrl($imageUrls['thumbnail']);
                $this->mangaRepository->save($manga, true);
                $changed++;
            }
        }


        return new JsonResponse(['changed' => $changed]);
    }

    /**
     * @throws GuzzleException
     */
    private function processAndSaveImage(string $imageUrl): array
    {
        $image = file_get_contents($this->projectDir . '/public' .$imageUrl);
        $tempImage = tmpfile();
        fwrite($tempImage, $image);
        $tempImagePath = stream_get_meta_data($tempImage)['uri'];

        // Générer un nom de fichier unique
        $originalFilename = pathinfo($imageUrl, PATHINFO_FILENAME);
        $safeFilename = $this->slugger->slug($originalFilename);
        $newFilename = $safeFilename . '-' . uniqid() . '.' . 'jpg';

        try {
            // Créer et sauvegarder la miniature
            $thumbnail = $this->imageManager->read($tempImagePath);
            $thumbnail->cover(300, 440);
            $thumbnail->save($this->projectDir . '/public/images/thumbnails/' . $newFilename, quality: 85);

            // Sauvegarder l'image en taille réelle
            //            $fullImage = $this->imageManager->read($tempImagePath);
            //            $fullImage->save($this->projectDir . '/public/images/full/' . $newFilename, quality: 90);

            // Fermer et supprimer le fichier temporaire
            fclose($tempImage);

            return [
                'full' => '/images/full/' . $newFilename,
                'thumbnail' => '/images/thumbnails/' . $newFilename
            ];

        } catch (FileException $e) {
            // Fermer le fichier temporaire en cas d'erreur
            fclose($tempImage);
            throw $e;
        }
    }
}
