<?php

namespace App\Jobs;

use App\Models\Project;
use App\ProjectLogger;
use Carbon\Carbon;
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 Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Process;

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

public $timeout = 800;
protected Project $project;
    protected Carbon $date;
    protected int $offset;

    public function __construct(Project $project,Carbon $date,int $offset)
    {
        $this->project = $project;
        $this->date = $date;
        $this->offset = $offset;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $command = [
            sprintf('%supdate_RDS.sh', base_path('../')),
            sprintf('--end_date=%s', $this->date->format('Y-m-d')),
            sprintf('--offset=%d', $this->offset),
            sprintf('--project_dir=%s', $this->project->download_path),
        ];

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

        if (!$process->isSuccessful()) {
            ProjectLogger::log($this->project, $process->getErrorOutput());
            return;
        }
        ProjectLogger::log($this->project, $process->getOutput());

    }

    /**
     * Handle the job for a date range
     */
    public static function fromDate(Project $project,Carbon $date,int $offset = 1):NullJob|ProjectDownloadRDSJob
    {
        $filename = $date->format('Y-m-d') . '.tif';
        if (!$project->downloads()->statusSuccess()->where(['name' => $filename])->exists()) {
            ProjectLogger::log($project, "The download $filename can't be processed. Please check it's status.");
            return new NullJob();
        }
        return new self($project,$date,$offset);
    }

}
