<?php

namespace App\Services\FMS;

use Exception;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GetVehicleActivityService
{
    protected string $url;
    protected string $channelName;
    protected string $password;
    protected string $username;
    protected array $inputParameters;

    public function __construct()
    {
        $this->url = config('fms_web_services.Vehicle_Activity.url');
        $this->password = config('fms_web_services.Vehicle_Activity.password');
        $this->username = config('fms_web_services.Vehicle_Activity.username');
        $this->channelName = 'fms_vehicle_activity';
    }

    public function setInputParameters(array $inputs): void
    {
        $this->inputParameters = $inputs;
    }

    /**
     * @throws Exception
     */
    public function run(): array
    {
        try {
            return $this->sendRequest();
        }
        catch (Exception $e) {
            Log::channel($this->channelName)
                ->error(get_class($this),
                    [
                        'message' => $e->getMessage(),
                    ]
                );

            throw $e;
        }
    }

    public function sendRequest(): array
    {
        $inputData = $this->makeInputParameters();

        return Http::withBody($inputData)
            ->throw()
            ->withoutVerifying()
            ->post($this->url)
            ->json();
    }

    private function makeInputParameters(): string
    {
        $inputData = $this->inputParameters + array(
            "username" => $this->username,
            "password" => $this->password,
            "minStopDuration" => 1,
        );

        return json_encode($inputData);
    }
}
