<?php

namespace App\Classes\Modules\Bookings\Processors;

use App\Classes\Modules\Bookings\Services\ListsBookings;
use App\Classes\Modules\Jobs\Processors\UpdateJobResultProcessor;
use App\Classes\General\Helper;
use App\Classes\Modules\Jobs\DataTransferObjects\JobSubmissionObject;
use App\Http\Resources\V2\ListBookingJobResource;
use Illuminate\Pagination\Paginator;

class ListBookingsJobProcessor
{

    /** @var ListsBookings */
    private $listsBookings;

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

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