<?php

namespace App\Livewire\Drawer\Album;

use App\Models\BatchMutation;
use App\Models\MutationBatch;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Bus;
use Livewire\Attributes\Locked;
use Livewire\Component;

class ProgressMonitor extends Component
{
    #[Locked]
    public BatchMutation $mutation;

    #[Locked]
    public float $progress;

    #[Locked]
    public int $processedJobs;

    #[Locked]
    public int $totalJobs;

    #[Locked]
    public int $failedJobs;

    #[Locked]
    public string $currentUrl;

    public function mounted(BatchMutation $mutation) : void {
        $this->mutation = $mutation;
        $this->currentUrl = url()->current();
    }

    public function monitorProgress() : void {
        $batch = Bus::findBatch($this->mutation->batch_id);
        $this->progress = $batch->progress();
        $this->totalJobs = $batch->totalJobs;
        $this->processedJobs = $batch->processedJobs();
        $this->failedJobs = $batch->failedJobs;

        if($batch == null || $batch->finished()) {
            $this->mutation->delete();
            $this->redirect($this->currentUrl, navigate: true);
        }
    }

    public function render(): View|Factory
    {
    $this->monitorProgress();
    return view('livewire.drawer.album.progress-monitor');
    }
}
