<?php
/**
 * ConfigApi
 * PHP version 7.2
 *
 * @category Class
 * @package  PrestaShop\Module\PolarisPrestaConnector\pol\api\lib
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * Polaris WebConnect
 *
 * L'API WebConnect vous permet d'interconnecter facilement votre solution Polaris avec un site Internet en permettant à ce dernier de télécharger votre catalogue, vos clients, votre fidélité       *Pour rappel, la spécification OpenAPI est une spécification de fichiers d'interface lisibles par une machine pour décrire, produire, consommer et visualiser les services Web REST de manière automatisée. Vous pouvez donc utiliser des outils comme [Swagger](https://editor.swagger.io/) pour générer automatiquement une bibliothèque cliente dans le langage de votre choix.*    **IMPORTANT / NOTE SUR LES ÉNUMÉRATEURS** : si vous générez un client avec OpenAPI Generator ou Swagger, appelez les API avec un User-Agent qui contient la chaîne 'enum_as_str;' afin que les énumérateurs soient gérés sous forme de chaîne de caractères et non de constantes entières.   **Voir la documentation générale : [https://nur1.pl-vega-0001.polarisgestionmag.net:3443/api?doc=WebConnect](https://nur1.pl-vega-0001.polarisgestionmag.net:3443/api?doc=WebConnect)**
 *
 * The version of the OpenAPI document: 14.2.99.65534
 * Contact: assistance@vega-info.fr
 * Generated by: https://openapi-generator.tech
 * Generator version: 7.8.0
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

namespace PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Api;

use GuzzleHttp\Psr7\MultipartStream;
use Http\Client\Common\Plugin\ErrorPlugin;
use Http\Client\Common\Plugin\RedirectPlugin;
use Http\Client\Common\PluginClient;
use Http\Client\Common\PluginClientFactory;
use Http\Client\Exception\HttpException;
use Http\Client\HttpAsyncClient;
use Http\Discovery\HttpAsyncClientDiscovery;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;
use Http\Message\RequestFactory;
use Http\Promise\Promise;
use PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ApiException;
use PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Configuration;
use PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\DebugPlugin;
use PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\HeaderSelector;
use PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ObjectSerializer;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface;
use function sprintf;

/**
 * ConfigApi Class Doc Comment
 *
 * @category Class
 * @package  PrestaShop\Module\PolarisPrestaConnector\pol\api\lib
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */
class ConfigApi
{
    /**
     * @var PluginClient
     */
    protected $httpClient;

    /**
     * @var PluginClient
     */
    protected $httpAsyncClient;

    /**
     * @var UriFactoryInterface
     */
    protected $uriFactory;

    /**
     * @var Configuration
     */
    protected $config;

    /**
     * @var HeaderSelector
     */
    protected $headerSelector;

    /**
     * @var int Host index
     */
    protected $hostIndex;

    /**
     * @var RequestFactoryInterface
     */
    protected $requestFactory;

    /**
     * @var StreamFactoryInterface
     */
    protected $streamFactory;

    public function __construct(
        ClientInterface $httpClient = null,
        Configuration $config = null,
        HttpAsyncClient $httpAsyncClient = null,
        UriFactoryInterface $uriFactory = null,
        RequestFactoryInterface $requestFactory = null,
        StreamFactoryInterface $streamFactory = null,
        HeaderSelector $selector = null,
        ?array $plugins = null,
        $hostIndex = 0
    ) {
        $this->config = $config ?? (new Configuration())->setHost('https://nur1.pl-vega-0001.polarisgestionmag.net:3443/api/WebConnect');
        $this->requestFactory = $requestFactory ?? Psr17FactoryDiscovery::findRequestFactory();
        $this->streamFactory = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory();

        $plugins = $plugins ?? [
            new RedirectPlugin(['strict' => true]),
            new ErrorPlugin(),
        ];

        if ($this->config->getDebug()) {
            $plugins[] = new DebugPlugin(fopen($this->config->getDebugFile(), 'ab'));
        }

        $this->httpClient = (new PluginClientFactory())->createClient(
            $httpClient ?? Psr18ClientDiscovery::find(),
            $plugins
        );

        $this->httpAsyncClient = (new PluginClientFactory())->createClient(
            $httpAsyncClient ?? HttpAsyncClientDiscovery::find(),
            $plugins
        );

        $this->uriFactory = $uriFactory ?? Psr17FactoryDiscovery::findUriFactory();

        $this->headerSelector = $selector ?? new HeaderSelector();

        $this->hostIndex = $hostIndex;
    }

    /**
     * Set the host index
     *
     * @param int $hostIndex Host index (required)
     */
    public function setHostIndex($hostIndex): void
    {
        $this->hostIndex = $hostIndex;
    }

    /**
     * Get the host index
     *
     * @return int Host index
     */
    public function getHostIndex()
    {
        return $this->hostIndex;
    }

    /**
     * @return Configuration
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * Operation configGetStruture
     *
     * Obtient les informations sur le connecteur mis à disposition par ces API
     *
     *
     * @throws \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoConnect
     */
    public function configGetStruture()
    {
        list($response) = $this->configGetStrutureWithHttpInfo();
        return $response;
    }

    /**
     * Operation configGetStrutureWithHttpInfo
     *
     * Obtient les informations sur le connecteur mis à disposition par ces API
     *
     *
     * @throws \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoConnect, HTTP status code, HTTP response headers (array of strings)
     */
    public function configGetStrutureWithHttpInfo()
    {
        $request = $this->configGetStrutureRequest();

        try {
            try {
                $response = $this->httpClient->sendRequest($request);
            } catch (HttpException $e) {
                $response = $e->getResponse();
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $response->getStatusCode(),
                        (string) $request->getUri()
                    ),
                    $request,
                    $response,
                    $e
                );
            } catch (ClientExceptionInterface $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    $request,
                    null,
                    $e
                );
            }

            $statusCode = $response->getStatusCode();

            switch($statusCode) {
                case 200:
                    if ('\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoConnect' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoConnect', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoConnect';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoConnect',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation configGetStrutureAsync
     *
     * Obtient les informations sur le connecteur mis à disposition par ces API
     *
     *
     * @throws \InvalidArgumentException
     * @return Promise
     */
    public function configGetStrutureAsync()
    {
        return $this->configGetStrutureAsyncWithHttpInfo()
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation configGetStrutureAsyncWithHttpInfo
     *
     * Obtient les informations sur le connecteur mis à disposition par ces API
     *
     *
     * @throws \InvalidArgumentException
     * @return Promise
     */
    public function configGetStrutureAsyncWithHttpInfo()
    {
        $returnType = '\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoConnect';
        $request = $this->configGetStrutureRequest();

        return $this->httpAsyncClient->sendAsyncRequest($request)
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function (HttpException $exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $exception->getRequest(),
                        $exception->getResponse(),
                        $exception
                    );
                }
            );
    }

    /**
     * Create request for operation 'configGetStruture'
     *
     *
     * @throws \InvalidArgumentException
     * @return RequestInterface
     */
    public function configGetStrutureRequest()
    {

        $resourcePath = '/Config/Struture';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = null;
        $multipart = false;





        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            '',
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('X-API-Key');
        if ($apiKey !== null) {
            $headers['X-API-Key'] = $apiKey;
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->config->getHost();

        $uri = $this->createUri($operationHost, $resourcePath, $queryParams);

        return $this->createRequest('GET', $uri, $headers, $httpBody);
    }

    /**
     * Operation configGetWebCatalogApp
     *
     * Obtient la configuration sur le WebCatalog si cet accès est paramétré pour l&#39;utilisation d&#39;un catalogue Web
     *
     *
     * @throws \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoCatalogue
     */
    public function configGetWebCatalogApp()
    {
        list($response) = $this->configGetWebCatalogAppWithHttpInfo();
        return $response;
    }

    /**
     * Operation configGetWebCatalogAppWithHttpInfo
     *
     * Obtient la configuration sur le WebCatalog si cet accès est paramétré pour l&#39;utilisation d&#39;un catalogue Web
     *
     *
     * @throws \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoCatalogue, HTTP status code, HTTP response headers (array of strings)
     */
    public function configGetWebCatalogAppWithHttpInfo()
    {
        $request = $this->configGetWebCatalogAppRequest();

        try {
            try {
                $response = $this->httpClient->sendRequest($request);
            } catch (HttpException $e) {
                $response = $e->getResponse();
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $response->getStatusCode(),
                        (string) $request->getUri()
                    ),
                    $request,
                    $response,
                    $e
                );
            } catch (ClientExceptionInterface $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    $request,
                    null,
                    $e
                );
            }

            $statusCode = $response->getStatusCode();

            switch($statusCode) {
                case 200:
                    if ('\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoCatalogue' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoCatalogue', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoCatalogue';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoCatalogue',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation configGetWebCatalogAppAsync
     *
     * Obtient la configuration sur le WebCatalog si cet accès est paramétré pour l&#39;utilisation d&#39;un catalogue Web
     *
     *
     * @throws \InvalidArgumentException
     * @return Promise
     */
    public function configGetWebCatalogAppAsync()
    {
        return $this->configGetWebCatalogAppAsyncWithHttpInfo()
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation configGetWebCatalogAppAsyncWithHttpInfo
     *
     * Obtient la configuration sur le WebCatalog si cet accès est paramétré pour l&#39;utilisation d&#39;un catalogue Web
     *
     *
     * @throws \InvalidArgumentException
     * @return Promise
     */
    public function configGetWebCatalogAppAsyncWithHttpInfo()
    {
        $returnType = '\PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\Model\InfoCatalogue';
        $request = $this->configGetWebCatalogAppRequest();

        return $this->httpAsyncClient->sendAsyncRequest($request)
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function (HttpException $exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $exception->getRequest(),
                        $exception->getResponse(),
                        $exception
                    );
                }
            );
    }

    /**
     * Create request for operation 'configGetWebCatalogApp'
     *
     *
     * @throws \InvalidArgumentException
     * @return RequestInterface
     */
    public function configGetWebCatalogAppRequest()
    {

        $resourcePath = '/Config/WebCatalogApp';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = null;
        $multipart = false;





        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            '',
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('X-API-Key');
        if ($apiKey !== null) {
            $headers['X-API-Key'] = $apiKey;
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->config->getHost();

        $uri = $this->createUri($operationHost, $resourcePath, $queryParams);

        return $this->createRequest('GET', $uri, $headers, $httpBody);
    }


    /**
     * @param string $method
     * @param string|UriInterface $uri
     * @param array $headers
     * @param string|StreamInterface|null $body
     *
     * @return RequestInterface
     */
    protected function createRequest(string $method, $uri, array $headers = [], $body = null): RequestInterface
    {
        if ($this->requestFactory instanceof RequestFactory) {
            return $this->requestFactory->createRequest(
                $method,
                $uri,
                $headers,
                $body
            );
        }

        if (is_string($body) && '' !== $body && null === $this->streamFactory) {
            throw new \RuntimeException('Cannot create request: A stream factory is required to create a request with a non-empty string body.');
        }

        $request = $this->requestFactory->createRequest($method, $uri);

        foreach ($headers as $key => $value) {
            $request = $request->withHeader($key, $value);
        }

        if (null !== $body && '' !== $body) {
            $request = $request->withBody(
                is_string($body) ? $this->streamFactory->createStream($body) : $body
            );
        }

        return $request;
    }

    private function createUri(
        string $operationHost,
        string $resourcePath,
        array $queryParams
    ): UriInterface {
        $parsedUrl = parse_url($operationHost);

        $host = $parsedUrl['host'] ?? null;
        $scheme = $parsedUrl['scheme'] ?? null;
        $basePath = $parsedUrl['path'] ?? null;
        $port = $parsedUrl['port'] ?? null;
        $user = $parsedUrl['user'] ?? null;
        $password = $parsedUrl['pass'] ?? null;

        $uri = $this->uriFactory->createUri($basePath . $resourcePath)
            ->withHost($host)
            ->withScheme($scheme)
            ->withPort($port)
            ->withQuery(ObjectSerializer::buildQuery($queryParams));

        if ($user) {
            $uri = $uri->withUserInfo($user, $password);
        }

        return $uri;
    }
}
