<?php

namespace FiloBlu\ActiveCampaign\Model\Connector;

use FiloBlu\ActiveCampaign\Helper\Data;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\ResponseFactory;
use Magento\Framework\DataObjectFactory;
use Magento\Framework\Webapi\Rest\Request;
use Psr\Log\LoggerInterface;

class Rest extends AbstractConnector
{

    /**
     * @var ResponseFactory
     */
    private $responseFactory;
    /**
     * @var
     */
    private $connection;

    /**
     * Rest constructor.
     * @param ResponseFactory $responseFactory
     * @param Data $helperData
     * @param DataObjectFactory $dataObjectFactory
     * @param LoggerInterface $logger
     */
    public function __construct(
        ResponseFactory $responseFactory,
        Data $helperData,
        DataObjectFactory $dataObjectFactory,
        LoggerInterface $logger
    ) {
        $this->responseFactory = $responseFactory;
        parent::__construct($helperData, $dataObjectFactory, $logger);
    }

    /**
     * @return ConnectorInterface
     */
    public function connect(): ConnectorInterface
    {
        if (!$this->connection) {
            $params = [
                'base_uri' => $this->helperData->getRestBaseUrl(),
                'headers'  => [
                    'Api-Token' => $this->helperData->getRestToken()
                ]
            ];
            $this->connection = new Client($params);
        }

        return $this;
    }

    /**
     * @return ConnectionInterface
     */
    public function disconnect(): ConnectionInterface
    {
        return $this;
    }

    /**
     * @param string $uriEndpoint
     * @param array $params
     * @param string $requestMethod
     * @return Response
     */
    public function doRequest(
        string $uriEndpoint,
        array $params = [],
        string $requestMethod = Request::HTTP_METHOD_GET
    ) {
        try {
            $response = $this->connection->request(
                $requestMethod,
                $uriEndpoint,
                $params
            );
        } catch (GuzzleException $exception) {
            /** @var Response $response */
            $response = $this->responseFactory->create([
                'status' => $exception->getCode(),
                'reason' => $exception->getMessage()
            ]);
        }

        return $response;
    }
}