<?php

namespace App\Classes\Modules\Documents\Processors;

use App\Classes\Modules\Documents\Services\ListsDocuments;
use App\Classes\Modules\Jobs\Processors\UpdateJobResultProcessor;
use App\Classes\General\Helper;
use App\Classes\Modules\Jobs\DataTransferObjects\JobSubmissionObject;
use App\Http\Resources\V2\ListDocumentJobResource;
use Illuminate\Pagination\Paginator;

class ListDocumentsJobProcessor
{

    /** @var ListsDocuments */
    private $listsDocuments;

    /** @var UpdateJobResultProcessor */
    private $updateJobResultProcessor;

    /**
     * ListDocumentsJobProcessor constructor.
     * @param ListsDocuments $listsDocuments
     * @param UpdateJobResultProcessor $updateJobResultProcessor
     */
    public function __construct(ListsDocuments $listsDocuments, UpdateJobResultProcessor $updateJobResultProcessor)
    {
        $this->listsDocuments = $listsDocuments;
        $this->updateJobResultProcessor = $updateJobResultProcessor;
    }

    /**
     * @param JobSubmissionObject $jobSubmissionObject
     * @return void
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\JobResourceNotFoundException
     */
    public function execute(JobSubmissionObject $jobSubmissionObject) {

        //$query = $this->listsDocuments->execute($this->listsDocuments->deserializeFilters($jobSubmissionObject->getPayload()['filters']), ['page' => $jobSubmissionObject->getPayload()['page']]);
        $query = $this->listsDocuments->execute($this->listsDocuments->deserializeFilters($jobSubmissionObject->getPayload()['filters']));

        if (isset($jobSubmissionObject->getPayload()['page'])) {
            $page = (int)$jobSubmissionObject->getPayload()['page'];
        } else {
            $page = 1;
        }
        Paginator::currentPageResolver(function () use ($page) {
            return $page;
        });

        foreach ($query->items() as $item) {
            $item['userInfo'] = $jobSubmissionObject->getUserInfo();
        }
        $resultCurrent = Helper::collectionResponse(ListDocumentJobResource::collection($query));
        $this->updateJobResultProcessor->execute($jobSubmissionObject, $resultCurrent);
    }
}

