<?php

namespace App\Services;

use App\Models\Episode;
use App\Models\Gallery;
use App\Models\Hentai;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

use Intervention\Image\Laravel\Facades\Image;
use Intervention\Image\Encoders\WebpEncoder;

class GalleryService
{

    public function createOrUpdateGallery(Request $request, Hentai $hentai, Episode $episode, int $episodeNumber, bool $override = false): void
    {
        $galleryInputNumber = $override ? 1 : $episodeNumber;

        if($request->hasFile('episodegallery'.$galleryInputNumber)) {

            $this->deleteOldGallery($episode);

            $this->createGalleryFolder($hentai);

            $counter = 0;
            foreach($request->file('episodegallery'.$galleryInputNumber) as $file) {
                $gallery = $this->createGallery($hentai, $episode, $episodeNumber, $counter);
                $this->saveGalleryImage($gallery, $file);
                $counter += 1;
            }
        }
    }

    private function createGalleryFolder(Hentai $hentai): void
    {
        // Create Folder for Image Upload
        if (! Storage::disk('public')->exists("/images/hentai/{$hentai->slug}")) {
            Storage::disk('public')->makeDirectory("/images/hentai/{$hentai->slug}");
        }
    }

    private function createGallery(Hentai $hentai, Episode $episode, int $episodeNumber, int $counter): Gallery
    {
        $gallery = new Gallery();
        $gallery->hentai_id = $hentai->id;
        $gallery->episode_id = $episode->id;
        $gallery->image_url = "/images/hentai/{$hentai->slug}/gallery-ep-{$episodeNumber}-{$counter}.webp";
        $gallery->thumbnail_url = "/images/hentai/{$hentai->slug}/gallery-ep-{$episodeNumber}-{$counter}-thumbnail.webp";
        $gallery->save();

        return $gallery;
    }

    private function saveGalleryImage(Gallery $gallery, $sourceImage): void
    {
        Image::read($sourceImage->getRealPath())
            ->cover(1920, 1080)
            ->encode(new WebpEncoder())
            ->save(Storage::disk('public')->path($gallery->image_url));

        Image::read($sourceImage->getRealPath())
            ->cover(960, 540)
            ->encode(new WebpEncoder())
            ->save(Storage::disk('public')->path($gallery->thumbnail_url));
    }

    private function deleteOldGallery(Episode $episode): void
    {
        $oldGallery = Gallery::where('episode_id', $episode->id)->get();
        foreach ($oldGallery as $oldImage) {
            Storage::disk('public')->delete($oldImage->image_url);
            Storage::disk('public')->delete($oldImage->thumbnail_url);
            $oldImage->forceDelete();
        }
    }
}
