<?php

namespace App\Classes\Modules\Transactions\Processors;

use App\Classes\Modules\Transactions\Services\ListsTransactions;
use App\Classes\Modules\Jobs\Processors\UpdateJobResultProcessor;
use App\Classes\General\Helper;
use App\Classes\Modules\Jobs\DataTransferObjects\JobSubmissionObject;
use App\Http\Resources\V2\ListTransactionJobResource;
use Illuminate\Pagination\Paginator;

class ListTransactionsJobProcessor
{

    /** @var ListsTransactions */
    private $listsTransactions;

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

    /**
     * ListTransactionsJobProcessor constructor.
     * @param ListsTransactions $listsTransactions
     * @param UpdateJobResultProcessor $updateJobResultProcessor
     */
    public function __construct(ListsTransactions $listsTransactions, UpdateJobResultProcessor $updateJobResultProcessor)
    {
        $this->listsTransactions = $listsTransactions;
        $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->listsTransactions->execute($this->listsTransactions->deserializeFilters($jobSubmissionObject->getPayload()['filters']), ['page' => $jobSubmissionObject->getPayload()['page']]);
        $query = $this->listsTransactions->execute($this->listsTransactions->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(ListTransactionJobResource::collection($query));
        $this->updateJobResultProcessor->execute($jobSubmissionObject, $resultCurrent);
    }
}

