<?php

namespace App\Classes\Modules\Jobs\Processors;


use App\Classes\Modules\Jobs\Services\UpdatesJobResult;
use App\Classes\Modules\Jobs\Services\FetchesJobResult;
use App\Classes\Exceptions\JobResourceNotFoundException;
use App\Classes\Modules\Jobs\DataTransferObjects\JobSubmissionObject;
use App\Classes\Modules\Jobs\DataTransferObjects\UpdateJobResultObject;

class UpdateJobResultProcessor
{

    /** @var FetchesJobResult */
    private $fetchesJobResult;

    /** @var UpdatesJobResult */
    private $updatesJobResult;

    /**
     * UpdateJobResultProcessor constructor.
     * @param FetchesJobResult $fetchesJobResult
     * @param UpdatesJobResult $updatesJobResult
     */
    public function __construct(FetchesJobResult $fetchesJobResult, UpdatesJobResult $updatesJobResult)
    {
        $this->fetchesJobResult = $fetchesJobResult;
        $this->updatesJobResult = $updatesJobResult;
    }

    /**
     * @param JobSubmissionObject $jobSubmissionObject
     * @param array $resultCurrent
     * @return void
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\JobResourceNotFoundException
     */
    public function execute(JobSubmissionObject $jobSubmissionObject, $resultCurrent) {
        $jobResultCurrent = $this->fetchesJobResult->execute(['job_id' => $jobSubmissionObject->getJobId()]);
        $resultCurrentJson = json_encode($resultCurrent);
        $resultSignatureCurrent = md5($resultCurrentJson);

        try{
            $jobResultExisting = $this->fetchesJobResult->execute(['request_signature' => $jobResultCurrent->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]);
            $resultSignatureExisting = $jobResultExisting->result_signature;
            //if($resultSignatureExisting != $resultSignatureCurrent){
                $this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $jobSubmissionObject->getJobCommandName(), $jobSubmissionObject->getJobCommand());
            //}
        } catch (JobResourceNotFoundException $exception){
            $this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $jobSubmissionObject->getJobCommandName(), $jobSubmissionObject->getJobCommand());
        }
    }

    private function updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $jobCommandName, $jobCommand){
        $updateJobResultObject = new UpdateJobResultObject(
            $resultCurrentJson,
            $resultSignatureCurrent,
            $jobCommandName,
            $jobCommand
        );
        $create = $this->updatesJobResult->execute($jobResultCurrent, $updateJobResultObject);
    }
}
