<?php

namespace App\Jobs;

use App\Models\Project;
use App\Models\ProjectDownload;
use App\ProjectLogger;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Carbon\Carbon;

use Illuminate\Support\Facades\Bus;
use Symfony\Component\Process\Process;

class ProjectDownloadTiffJob implements ShouldQueue
{
    use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected Carbon $date;
    protected ProjectDownload $download;
    protected $days = 1;

    /**
     * Create a new job instance.
     */
    public function __construct(ProjectDownload $download, Carbon $date)
    {
        $this->date = $date;
        $this->download = $download;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {

        $command = [
            sprintf('%srunpython.sh', base_path('../')),
            sprintf('--date=%s', $this->date->format('Y-m-d')),
            sprintf('--days=%d', $this->days),
            sprintf('--project_dir=%s', $this->download->project->download_path),
        ];

        $process = new Process($command);
        $process->setTimeout(600);
        $process->run();

        $project = $this->download->project;

        if (!$process->isSuccessful()) {
            ProjectLogger::log($project, $process->getErrorOutput());
            $this->download->setStatusFailed();
            return;
        }
        // Success
        ProjectLogger::log($project, $process->getOutput());
        $this->download->setStatusSuccess();
        dispatch(ProjectDownloadRDSJob::fromDate($this->download->project, $this->date, $this->days));
    }

    public static function handleForDate(Project $project, Carbon $date)
    {
        $filename = $date->format('Y-m-d') . '.tif';
        if ($project->downloads()->statusSuccess()->where(['name' => $filename])->exists()) {
            return new NullJob();
        }

        $path = $project->download_path . '/merged_final_tif/' . $filename;
        return new self(
            $project->downloads()->create([
                'name' => $filename,
                'path' => $path,
            ]),
            $date
        );
    }
}
