<?php

namespace App\Livewire\Album;

use App\Importers\Image\Jobs\FinishImageModification;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Bus;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;
use App\Models\Album;
use App\Models\Image;
use App\Importers\Image\Jobs\RotateImage;
use App\Importers\Image\Jobs\GenerateFullscreen;
use App\Importers\Image\Jobs\GenerateThumbnail;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;

class Show extends Component
{
    #[Locked]
    public Album $album;

    #[Locked]
    public EloquentCollection $images;

    public function mount(Album $album): void {
        $this->album = $album;
        $this->images = $album->images;
    }

    #[On('image.rotate')]
    public function rotate(int $image_id, string $direction):void {
        $degrees = match ($direction) {
            'cw' => -90,
            'ccw' => 90,
            default => 0,
        };
        $this->dispatchRotateJob(Image::findOrFail($image_id), $degrees);

        $this->redirect(route('album.show', $this->album), navigate: true);
    }

    private function dispatchRotateJob(Image $image, int $degrees) : void {
        $image->update([
            'isProcessing' => true,
        ]);

        Bus::chain([
            new RotateImage($image, $degrees),
            Bus::batch([
                new GenerateFullscreen($image),
                new GenerateThumbnail($image),
            ]),
            new FinishImageModification($image),
        ])->dispatch();
    }

    #[Title('Show Album')] 
    public function render(): View|Factory
    {
        return view('livewire.album.show');
    }
}
