<?php

namespace App\Jobs;

use App\Livewire\Forms\MailingForm;
use App\Models\ProjectReport;
use App\ProjectLogger;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Symfony\Component\Process\Process;

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

    public $timeout = 600;
    private ProjectReport $projectReport;
    private bool $sendMail;

    private bool $isTestReport;

    /**
     * Create a new job instance.
     */
    public function __construct(ProjectReport $projectReport, $sendMail = false, $isTestReport = false)
    {
        $this->projectReport = $projectReport;
        $this->sendMail = $sendMail;
        $this->isTestReport = $isTestReport;
    }

    /**
     * Execute the job.
     */
    public function handle()
    {
        // TODO check the changements due to migration
        $projectFolder = base_path('../');

        $command = [
            sprintf('%sbuild_report.sh', $projectFolder),
            sprintf('--filename=%s', $this->projectReport->getFullPathName()),
            sprintf('--report_date=%s', $this->projectReport->getReportDate()),
            sprintf('--mail_day=%s', $this->isTestReport? Carbon::yesterday()->dayName: $this->projectReport->project->mail_day),
            sprintf('--data_dir=%s', $this->projectReport->project->download_path),
            sprintf('--borders=%s', $this->projectReport->project->borders ? 'True' : 'False'),
        ];
        ProjectLogger::log($this->projectReport->project, 'command:'. print_r($command, true));

        // Convert commands array to a single string

        $process = new Process($command);
        $process->setTimeout(600);
        $currentPath = '/usr/bin:/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin/Users/mfolkerts/anaconda3/bin:/Library/Apple/usr/bin';

        $process->setEnv(['PATH' => $currentPath.':/usr/local/Cellar/pandoc/3.1.8/bin/pandoc']);
        $process->start();
        try {
            $myOutput = [];
            $process->wait(function ($type, $buffer) use (&$myOutput) {
//                $this->stream(to: 'processOutput', content: $buffer);
                $myOutput[] = $buffer;
                ProjectLogger::log($this->projectReport->project, $buffer);
            });
            $this->processOutput = collect($myOutput)->join('\n');
            $this->projectReport->setStatusSuccess();
        } catch (ProcessFailedException $exception) {
            echo $exception->getMessage();
            $this->projectReport->setStatusFailed();
        }

        $this->sendMail();
    }

    private function sendMail(): void
    {
        if ($this->sendMail && $this->projectReport->statusIsSuccessful()) {
            logger('sendMail');
            MailingForm::saveAndSendMailing(
                $this->projectReport,
                $this->projectReport->project->mail_subject,
                $this->projectReport->project->mail_template,
                $this->projectReport->project->emailRecipients()->get(['email', 'name'])->toArray()
            );
        }
    }
}
