<?php
/**
 * MediaApi
 * 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.1.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;

/**
 * MediaApi Class Doc Comment
 *
 * @category Class
 * @package  PrestaShop\Module\PolarisPrestaConnector\pol\api\lib
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */
class MediaApi
{
    /**
     * @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 mediaGetPhoto
     *
     * Obtient la photo correspondant à l&#39;identifiant fourni
     *
     * @param  int $no_photo Numéro de la photo que vous souhaitez obtenir (required)
     * @param  PhotoSize $photo_size Taille de l&#39;image souhaitée, si non spécifiée, renvoi la taille paramétrée sur le système (optional)
     *
     * @throws \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return void
     */
    public function mediaGetPhoto($no_photo, $photo_size = null)
    {
        $this->mediaGetPhotoWithHttpInfo($no_photo, $photo_size);
    }

    /**
     * Operation mediaGetPhotoWithHttpInfo
     *
     * Obtient la photo correspondant à l&#39;identifiant fourni
     *
     * @param  int $no_photo Numéro de la photo que vous souhaitez obtenir (required)
     * @param  PhotoSize $photo_size Taille de l&#39;image souhaitée, si non spécifiée, renvoi la taille paramétrée sur le système (optional)
     *
     * @throws \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of null, HTTP status code, HTTP response headers (array of strings)
     */
    public function mediaGetPhotoWithHttpInfo($no_photo, $photo_size = null)
    {
        $request = $this->mediaGetPhotoRequest($no_photo, $photo_size);

        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();

            return [null, $statusCode, $response->getHeaders()];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
            }
            throw $e;
        }
    }

    /**
     * Operation mediaGetPhotoAsync
     *
     * Obtient la photo correspondant à l&#39;identifiant fourni
     *
     * @param  int $no_photo Numéro de la photo que vous souhaitez obtenir (required)
     * @param  PhotoSize $photo_size Taille de l&#39;image souhaitée, si non spécifiée, renvoi la taille paramétrée sur le système (optional)
     *
     * @throws \InvalidArgumentException
     * @return Promise
     */
    public function mediaGetPhotoAsync($no_photo, $photo_size = null)
    {
        return $this->mediaGetPhotoAsyncWithHttpInfo($no_photo, $photo_size)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation mediaGetPhotoAsyncWithHttpInfo
     *
     * Obtient la photo correspondant à l&#39;identifiant fourni
     *
     * @param  int $no_photo Numéro de la photo que vous souhaitez obtenir (required)
     * @param  PhotoSize $photo_size Taille de l&#39;image souhaitée, si non spécifiée, renvoi la taille paramétrée sur le système (optional)
     *
     * @throws \InvalidArgumentException
     * @return Promise
     */
    public function mediaGetPhotoAsyncWithHttpInfo($no_photo, $photo_size = null)
    {
        $returnType = '';
        $request = $this->mediaGetPhotoRequest($no_photo, $photo_size);

        return $this->httpAsyncClient->sendAsyncRequest($request)
            ->then(
                function ($response) use ($returnType) {
                    return [null, $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 'mediaGetPhoto'
     *
     * @param  int $no_photo Numéro de la photo que vous souhaitez obtenir (required)
     * @param  PhotoSize $photo_size Taille de l&#39;image souhaitée, si non spécifiée, renvoi la taille paramétrée sur le système (optional)
     *
     * @throws \InvalidArgumentException
     * @return RequestInterface
     */
    public function mediaGetPhotoRequest($no_photo, $photo_size = null)
    {
        // verify the required parameter 'no_photo' is set
        if ($no_photo === null || (is_array($no_photo) && count($no_photo) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $no_photo when calling mediaGetPhoto'
            );
        }

        $resourcePath = '/Media/Photo';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = null;
        $multipart = false;

        // query params
        if ($no_photo !== null) {
            if('form' === 'form' && is_array($no_photo)) {
                foreach($no_photo as $key => $value) {
                    $queryParams[$key] = $value;
                }
            }
            else {
                $queryParams['noPhoto'] = $no_photo;
            }
        }
        // query params
        if ($photo_size !== null) {
            if('form' === 'form' && is_array($photo_size)) {
                foreach($photo_size as $key => $value) {
                    $queryParams[$key] = $value;
                }
            }
            else {
                $queryParams['photoSize'] = $photo_size;
            }
        }




        $headers = $this->headerSelector->selectHeaders(
            ['image'],
            '',
            $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 mediaPutUrl
     *
     * Poste les URL du site
     *
     * @param  string $sku Code Polaris, Gencod Fournisseur ou GTIN (required)
     * @param  MediaTypeUrl $type_url Type de URL (required)
     * @param  string $body Url complète de la photo ou du produit sur le site  (url) (required)
     * @param  int $index Index de la photo (optional, default to 0)
     *
     * @throws \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return void
     */
    public function mediaPutUrl($sku, $type_url, $body, $index = 0)
    {
        $this->mediaPutUrlWithHttpInfo($sku, $type_url, $body, $index);
    }

    /**
     * Operation mediaPutUrlWithHttpInfo
     *
     * Poste les URL du site
     *
     * @param  string $sku Code Polaris, Gencod Fournisseur ou GTIN (required)
     * @param  MediaTypeUrl $type_url Type de URL (required)
     * @param  string $body Url complète de la photo ou du produit sur le site  (url) (required)
     * @param  int $index Index de la photo (optional, default to 0)
     *
     * @throws \PrestaShop\Module\PolarisPrestaConnector\pol\api\lib\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of null, HTTP status code, HTTP response headers (array of strings)
     */
    public function mediaPutUrlWithHttpInfo($sku, $type_url, $body, $index = 0)
    {
        $request = $this->mediaPutUrlRequest($sku, $type_url, $body, $index);

        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();

            return [null, $statusCode, $response->getHeaders()];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
            }
            throw $e;
        }
    }

    /**
     * Operation mediaPutUrlAsync
     *
     * Poste les URL du site
     *
     * @param  string $sku Code Polaris, Gencod Fournisseur ou GTIN (required)
     * @param  MediaTypeUrl $type_url Type de URL (required)
     * @param  string $body Url complète de la photo ou du produit sur le site  (url) (required)
     * @param  int $index Index de la photo (optional, default to 0)
     *
     * @throws \InvalidArgumentException
     * @return Promise
     */
    public function mediaPutUrlAsync($sku, $type_url, $body, $index = 0)
    {
        return $this->mediaPutUrlAsyncWithHttpInfo($sku, $type_url, $body, $index)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation mediaPutUrlAsyncWithHttpInfo
     *
     * Poste les URL du site
     *
     * @param  string $sku Code Polaris, Gencod Fournisseur ou GTIN (required)
     * @param  MediaTypeUrl $type_url Type de URL (required)
     * @param  string $body Url complète de la photo ou du produit sur le site  (url) (required)
     * @param  int $index Index de la photo (optional, default to 0)
     *
     * @throws \InvalidArgumentException
     * @return Promise
     */
    public function mediaPutUrlAsyncWithHttpInfo($sku, $type_url, $body, $index = 0)
    {
        $returnType = '';
        $request = $this->mediaPutUrlRequest($sku, $type_url, $body, $index);

        return $this->httpAsyncClient->sendAsyncRequest($request)
            ->then(
                function ($response) use ($returnType) {
                    return [null, $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 'mediaPutUrl'
     *
     * @param  string $sku Code Polaris, Gencod Fournisseur ou GTIN (required)
     * @param  MediaTypeUrl $type_url Type de URL (required)
     * @param  string $body Url complète de la photo ou du produit sur le site  (url) (required)
     * @param  int $index Index de la photo (optional, default to 0)
     *
     * @throws \InvalidArgumentException
     * @return RequestInterface
     */
    public function mediaPutUrlRequest($sku, $type_url, $body, $index = 0)
    {
        // verify the required parameter 'sku' is set
        if ($sku === null || (is_array($sku) && count($sku) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $sku when calling mediaPutUrl'
            );
        }
        // verify the required parameter 'type_url' is set
        if ($type_url === null || (is_array($type_url) && count($type_url) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $type_url when calling mediaPutUrl'
            );
        }
        // verify the required parameter 'body' is set
        if ($body === null || (is_array($body) && count($body) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $body when calling mediaPutUrl'
            );
        }

        $resourcePath = '/Media/Url';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = null;
        $multipart = false;

        // query params
        if ($sku !== null) {
            if('form' === 'form' && is_array($sku)) {
                foreach($sku as $key => $value) {
                    $queryParams[$key] = $value;
                }
            }
            else {
                $queryParams['sku'] = $sku;
            }
        }
        // query params
        if ($type_url !== null) {
            if('form' === 'form' && is_array($type_url)) {
                foreach($type_url as $key => $value) {
                    $queryParams[$key] = $value;
                }
            }
            else {
                $queryParams['TypeUrl'] = $type_url;
            }
        }
        // query params
        if ($index !== null) {
            if('form' === 'form' && is_array($index)) {
                foreach($index as $key => $value) {
                    $queryParams[$key] = $value;
                }
            }
            else {
                $queryParams['Index'] = $index;
            }
        }




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

        // for model (json/xml)
        if (isset($body)) {
            if ($headers['Content-Type'] === 'application/json') {
                $httpBody = json_encode(ObjectSerializer::sanitizeForSerialization($body));
            } else {
                $httpBody = $body;
            }
        } elseif (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('PUT', $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;
    }
}
