<?php
/**
 * PurchaseInvoiceApi
 * PHP version 7.2
 *
 * @category Class
 * @package  EConnect\Psb
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * PSB API 1.0
 *
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 1.0
 * Contact: techsupport@econnect.eu
 * Generated by: https://openapi-generator.tech
 * OpenAPI Generator version: 5.2.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 EConnect\Psb\Api;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use EConnect\Psb\ApiException;
use EConnect\Psb\Configuration;
use EConnect\Psb\HeaderSelector;
use EConnect\Psb\ObjectSerializer;

/**
 * PurchaseInvoiceApi Class Doc Comment
 *
 * @category Class
 * @package  EConnect\Psb
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */
class PurchaseInvoiceApi
{
    /**
     * @var ClientInterface
     */
    protected $client;

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

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

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

    /**
     * @param ClientInterface $client
     * @param Configuration   $config
     * @param HeaderSelector  $selector
     * @param int             $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
     */
    public function __construct(
        ClientInterface $client = null,
        Configuration $config = null,
        HeaderSelector $selector = null,
        $hostIndex = 0
    ) {
        $this->client = $client ?: new Client();
        $this->config = $config ?: new Configuration();
        $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 deletePurchaseInvoice
     *
     * Delete purchase invoice.
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  string $document_id The service bus documentId (required)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return void
     */
    public function deletePurchaseInvoice($party_id, $document_id)
    {
        $this->deletePurchaseInvoiceWithHttpInfo($party_id, $document_id);
    }

    /**
     * Operation deletePurchaseInvoiceWithHttpInfo
     *
     * Delete purchase invoice.
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  string $document_id The service bus documentId (required)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of null, HTTP status code, HTTP response headers (array of strings)
     */
    public function deletePurchaseInvoiceWithHttpInfo($party_id, $document_id)
    {
        $request = $this->deletePurchaseInvoiceRequest($party_id, $document_id);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

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

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

    /**
     * Operation deletePurchaseInvoiceAsync
     *
     * Delete purchase invoice.
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  string $document_id The service bus documentId (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function deletePurchaseInvoiceAsync($party_id, $document_id)
    {
        return $this->deletePurchaseInvoiceAsyncWithHttpInfo($party_id, $document_id)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation deletePurchaseInvoiceAsyncWithHttpInfo
     *
     * Delete purchase invoice.
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  string $document_id The service bus documentId (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function deletePurchaseInvoiceAsyncWithHttpInfo($party_id, $document_id)
    {
        $returnType = '';
        $request = $this->deletePurchaseInvoiceRequest($party_id, $document_id);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    return [null, $response->getStatusCode(), $response->getHeaders()];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'deletePurchaseInvoice'
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  string $document_id The service bus documentId (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function deletePurchaseInvoiceRequest($party_id, $document_id)
    {
        // verify the required parameter 'party_id' is set
        if ($party_id === null || (is_array($party_id) && count($party_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $party_id when calling deletePurchaseInvoice'
            );
        }
        if (!preg_match("/[A-Za-z0-9-=:]+/", $party_id)) {
            throw new \InvalidArgumentException("invalid value for \"party_id\" when calling PurchaseInvoiceApi.deletePurchaseInvoice, must conform to the pattern /[A-Za-z0-9-=:]+/.");
        }

        // verify the required parameter 'document_id' is set
        if ($document_id === null || (is_array($document_id) && count($document_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $document_id when calling deletePurchaseInvoice'
            );
        }
        if (strlen($document_id) > 256) {
            throw new \InvalidArgumentException('invalid length for "$document_id" when calling PurchaseInvoiceApi.deletePurchaseInvoice, must be smaller than or equal to 256.');
        }


        $resourcePath = '/api/v1/{partyId}/purchaseInvoice/{documentId}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($party_id !== null) {
            $resourcePath = str_replace(
                '{' . 'partyId' . '}',
                ObjectSerializer::toPathValue($party_id),
                $resourcePath
            );
        }
        // path params
        if ($document_id !== null) {
            $resourcePath = str_replace(
                '{' . 'documentId' . '}',
                ObjectSerializer::toPathValue($document_id),
                $resourcePath
            );
        }


        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                []
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                [],
                []
            );
        }

        // 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 = \GuzzleHttp\json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = \GuzzleHttp\Psr7\build_query($formParams);
            }
        }

        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }
        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('Subscription-Key');
        if ($apiKey !== null) {
            $headers['Subscription-Key'] = $apiKey;
        }

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

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

        $query = \GuzzleHttp\Psr7\build_query($queryParams);
        return new Request(
            'DELETE',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation downloadPurchaseInvoice
     *
     * Download purchase invoice.
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     * @param  string $target_format The target format. (optional)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return |\SplFileObject
     */
    public function downloadPurchaseInvoice($party_id, $document_id, $target_format = null)
    {
        list($response) = $this->downloadPurchaseInvoiceWithHttpInfo($party_id, $document_id, $target_format);
        return $response;
    }

    /**
     * Operation downloadPurchaseInvoiceWithHttpInfo
     *
     * Download purchase invoice.
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     * @param  string $target_format The target format. (optional)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of |\SplFileObject, HTTP status code, HTTP response headers (array of strings)
     */
    public function downloadPurchaseInvoiceWithHttpInfo($party_id, $document_id, $target_format = null)
    {
        $request = $this->downloadPurchaseInvoiceRequest($party_id, $document_id, $target_format);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\SplFileObject' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\SplFileObject', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\SplFileObject';
            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(),
                        '\SplFileObject',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation downloadPurchaseInvoiceAsync
     *
     * Download purchase invoice.
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     * @param  string $target_format The target format. (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function downloadPurchaseInvoiceAsync($party_id, $document_id, $target_format = null)
    {
        return $this->downloadPurchaseInvoiceAsyncWithHttpInfo($party_id, $document_id, $target_format)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation downloadPurchaseInvoiceAsyncWithHttpInfo
     *
     * Download purchase invoice.
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     * @param  string $target_format The target format. (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function downloadPurchaseInvoiceAsyncWithHttpInfo($party_id, $document_id, $target_format = null)
    {
        $returnType = '\SplFileObject';
        $request = $this->downloadPurchaseInvoiceRequest($party_id, $document_id, $target_format);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->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 ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'downloadPurchaseInvoice'
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     * @param  string $target_format The target format. (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function downloadPurchaseInvoiceRequest($party_id, $document_id, $target_format = null)
    {
        // verify the required parameter 'party_id' is set
        if ($party_id === null || (is_array($party_id) && count($party_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $party_id when calling downloadPurchaseInvoice'
            );
        }
        if (!preg_match("/[A-Za-z0-9-=:]+/", $party_id)) {
            throw new \InvalidArgumentException("invalid value for \"party_id\" when calling PurchaseInvoiceApi.downloadPurchaseInvoice, must conform to the pattern /[A-Za-z0-9-=:]+/.");
        }

        // verify the required parameter 'document_id' is set
        if ($document_id === null || (is_array($document_id) && count($document_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $document_id when calling downloadPurchaseInvoice'
            );
        }
        if (strlen($document_id) > 256) {
            throw new \InvalidArgumentException('invalid length for "$document_id" when calling PurchaseInvoiceApi.downloadPurchaseInvoice, must be smaller than or equal to 256.');
        }

        if ($target_format !== null && !preg_match("/[A-Za-z0-9-:.]{1,}[#]{2}[A-Za-z0-9-:.#*]{1,}|^$/", $target_format)) {
            throw new \InvalidArgumentException("invalid value for \"target_format\" when calling PurchaseInvoiceApi.downloadPurchaseInvoice, must conform to the pattern /[A-Za-z0-9-:.]{1,}[#]{2}[A-Za-z0-9-:.#*]{1,}|^$/.");
        }


        $resourcePath = '/api/v1/{partyId}/purchaseInvoice/{documentId}/download';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

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


        // path params
        if ($party_id !== null) {
            $resourcePath = str_replace(
                '{' . 'partyId' . '}',
                ObjectSerializer::toPathValue($party_id),
                $resourcePath
            );
        }
        // path params
        if ($document_id !== null) {
            $resourcePath = str_replace(
                '{' . 'documentId' . '}',
                ObjectSerializer::toPathValue($document_id),
                $resourcePath
            );
        }


        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/xml', 'application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/xml', 'application/json'],
                []
            );
        }

        // 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 = \GuzzleHttp\json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = \GuzzleHttp\Psr7\build_query($formParams);
            }
        }

        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }
        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('Subscription-Key');
        if ($apiKey !== null) {
            $headers['Subscription-Key'] = $apiKey;
        }

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

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

        $query = \GuzzleHttp\Psr7\build_query($queryParams);
        return new Request(
            'GET',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation getPurchaseInvoiceStatuses
     *
     * Get purchase invoice statuses.
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return |\EConnect\Psb\Model\DocumentStatus[]
     */
    public function getPurchaseInvoiceStatuses($party_id, $document_id)
    {
        list($response) = $this->getPurchaseInvoiceStatusesWithHttpInfo($party_id, $document_id);
        return $response;
    }

    /**
     * Operation getPurchaseInvoiceStatusesWithHttpInfo
     *
     * Get purchase invoice statuses.
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of |\EConnect\Psb\Model\DocumentStatus[], HTTP status code, HTTP response headers (array of strings)
     */
    public function getPurchaseInvoiceStatusesWithHttpInfo($party_id, $document_id)
    {
        $request = $this->getPurchaseInvoiceStatusesRequest($party_id, $document_id);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\EConnect\Psb\Model\DocumentStatus[]' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\EConnect\Psb\Model\DocumentStatus[]', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\EConnect\Psb\Model\DocumentStatus[]';
            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(),
                        '\EConnect\Psb\Model\DocumentStatus[]',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation getPurchaseInvoiceStatusesAsync
     *
     * Get purchase invoice statuses.
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getPurchaseInvoiceStatusesAsync($party_id, $document_id)
    {
        return $this->getPurchaseInvoiceStatusesAsyncWithHttpInfo($party_id, $document_id)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getPurchaseInvoiceStatusesAsyncWithHttpInfo
     *
     * Get purchase invoice statuses.
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getPurchaseInvoiceStatusesAsyncWithHttpInfo($party_id, $document_id)
    {
        $returnType = '\EConnect\Psb\Model\DocumentStatus[]';
        $request = $this->getPurchaseInvoiceStatusesRequest($party_id, $document_id);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->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 ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'getPurchaseInvoiceStatuses'
     *
     * @param  string $party_id The recipient partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getPurchaseInvoiceStatusesRequest($party_id, $document_id)
    {
        // verify the required parameter 'party_id' is set
        if ($party_id === null || (is_array($party_id) && count($party_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $party_id when calling getPurchaseInvoiceStatuses'
            );
        }
        if (!preg_match("/[A-Za-z0-9-=:]+/", $party_id)) {
            throw new \InvalidArgumentException("invalid value for \"party_id\" when calling PurchaseInvoiceApi.getPurchaseInvoiceStatuses, must conform to the pattern /[A-Za-z0-9-=:]+/.");
        }

        // verify the required parameter 'document_id' is set
        if ($document_id === null || (is_array($document_id) && count($document_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $document_id when calling getPurchaseInvoiceStatuses'
            );
        }
        if (strlen($document_id) > 256) {
            throw new \InvalidArgumentException('invalid length for "$document_id" when calling PurchaseInvoiceApi.getPurchaseInvoiceStatuses, must be smaller than or equal to 256.');
        }


        $resourcePath = '/api/v1/{partyId}/purchaseInvoice/{documentId}/status';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($party_id !== null) {
            $resourcePath = str_replace(
                '{' . 'partyId' . '}',
                ObjectSerializer::toPathValue($party_id),
                $resourcePath
            );
        }
        // path params
        if ($document_id !== null) {
            $resourcePath = str_replace(
                '{' . 'documentId' . '}',
                ObjectSerializer::toPathValue($document_id),
                $resourcePath
            );
        }


        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                []
            );
        }

        // 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 = \GuzzleHttp\json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = \GuzzleHttp\Psr7\build_query($formParams);
            }
        }

        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }
        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('Subscription-Key');
        if ($apiKey !== null) {
            $headers['Subscription-Key'] = $apiKey;
        }

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

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

        $query = \GuzzleHttp\Psr7\build_query($queryParams);
        return new Request(
            'GET',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation recognizePurchaseInvoice
     *
     * Recognize purchase invoice.
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  \SplFileObject $file file (required)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return |\EConnect\Psb\Model\Document
     */
    public function recognizePurchaseInvoice($party_id, $file)
    {
        list($response) = $this->recognizePurchaseInvoiceWithHttpInfo($party_id, $file);
        return $response;
    }

    /**
     * Operation recognizePurchaseInvoiceWithHttpInfo
     *
     * Recognize purchase invoice.
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  \SplFileObject $file (required)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of |\EConnect\Psb\Model\Document, HTTP status code, HTTP response headers (array of strings)
     */
    public function recognizePurchaseInvoiceWithHttpInfo($party_id, $file)
    {
        $request = $this->recognizePurchaseInvoiceRequest($party_id, $file);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\EConnect\Psb\Model\Document' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\EConnect\Psb\Model\Document', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\EConnect\Psb\Model\Document';
            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(),
                        '\EConnect\Psb\Model\Document',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation recognizePurchaseInvoiceAsync
     *
     * Recognize purchase invoice.
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  \SplFileObject $file (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function recognizePurchaseInvoiceAsync($party_id, $file)
    {
        return $this->recognizePurchaseInvoiceAsyncWithHttpInfo($party_id, $file)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation recognizePurchaseInvoiceAsyncWithHttpInfo
     *
     * Recognize purchase invoice.
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  \SplFileObject $file (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function recognizePurchaseInvoiceAsyncWithHttpInfo($party_id, $file)
    {
        $returnType = '\EConnect\Psb\Model\Document';
        $request = $this->recognizePurchaseInvoiceRequest($party_id, $file);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->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 ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'recognizePurchaseInvoice'
     *
     * @param  string $party_id The recipient partyId (required)
     * @param  \SplFileObject $file (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function recognizePurchaseInvoiceRequest($party_id, $file)
    {
        // verify the required parameter 'party_id' is set
        if ($party_id === null || (is_array($party_id) && count($party_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $party_id when calling recognizePurchaseInvoice'
            );
        }
        if (!preg_match("/[A-Za-z0-9-=:]+/", $party_id)) {
            throw new \InvalidArgumentException("invalid value for \"party_id\" when calling PurchaseInvoiceApi.recognizePurchaseInvoice, must conform to the pattern /[A-Za-z0-9-=:]+/.");
        }

        // verify the required parameter 'file' is set
        if ($file === null || (is_array($file) && count($file) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $file when calling recognizePurchaseInvoice'
            );
        }

        $resourcePath = '/api/v1/{partyId}/purchaseInvoice/recognize';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($party_id !== null) {
            $resourcePath = str_replace(
                '{' . 'partyId' . '}',
                ObjectSerializer::toPathValue($party_id),
                $resourcePath
            );
        }

        // form params
        if ($file !== null) {
            $multipart = true;
            $formParams['file'] = [];
            $paramFiles = is_array($file) ? $file : [$file];
            foreach ($paramFiles as $paramFile) {
                $formParams['file'][] = \GuzzleHttp\Psr7\try_fopen(
                    ObjectSerializer::toFormValue($paramFile),
                    'rb'
                );
            }
        }

        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                ['multipart/form-data']
            );
        }

        // 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 = \GuzzleHttp\json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = \GuzzleHttp\Psr7\build_query($formParams);
            }
        }

        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }
        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('Subscription-Key');
        if ($apiKey !== null) {
            $headers['Subscription-Key'] = $apiKey;
        }

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

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

        $query = \GuzzleHttp\Psr7\build_query($queryParams);
        return new Request(
            'POST',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation sendInvoiceResponse
     *
     * Send invoice response to let the seller know the status of the received invoice.
     *
     * @param  string $party_id Your partyId (buyer). (required)
     * @param  string $document_id DocumentId that the response is about. (required)
     * @param  \EConnect\Psb\Model\InvoiceResponse $invoice_response Invoice response message. (required)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return |\EConnect\Psb\Model\Document
     */
    public function sendInvoiceResponse($party_id, $document_id, $invoice_response)
    {
        list($response) = $this->sendInvoiceResponseWithHttpInfo($party_id, $document_id, $invoice_response);
        return $response;
    }

    /**
     * Operation sendInvoiceResponseWithHttpInfo
     *
     * Send invoice response to let the seller know the status of the received invoice.
     *
     * @param  string $party_id Your partyId (buyer). (required)
     * @param  string $document_id DocumentId that the response is about. (required)
     * @param  \EConnect\Psb\Model\InvoiceResponse $invoice_response Invoice response message. (required)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of |\EConnect\Psb\Model\Document, HTTP status code, HTTP response headers (array of strings)
     */
    public function sendInvoiceResponseWithHttpInfo($party_id, $document_id, $invoice_response)
    {
        $request = $this->sendInvoiceResponseRequest($party_id, $document_id, $invoice_response);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\EConnect\Psb\Model\Document' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\EConnect\Psb\Model\Document', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\EConnect\Psb\Model\Document';
            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(),
                        '\EConnect\Psb\Model\Document',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation sendInvoiceResponseAsync
     *
     * Send invoice response to let the seller know the status of the received invoice.
     *
     * @param  string $party_id Your partyId (buyer). (required)
     * @param  string $document_id DocumentId that the response is about. (required)
     * @param  \EConnect\Psb\Model\InvoiceResponse $invoice_response Invoice response message. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function sendInvoiceResponseAsync($party_id, $document_id, $invoice_response)
    {
        return $this->sendInvoiceResponseAsyncWithHttpInfo($party_id, $document_id, $invoice_response)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation sendInvoiceResponseAsyncWithHttpInfo
     *
     * Send invoice response to let the seller know the status of the received invoice.
     *
     * @param  string $party_id Your partyId (buyer). (required)
     * @param  string $document_id DocumentId that the response is about. (required)
     * @param  \EConnect\Psb\Model\InvoiceResponse $invoice_response Invoice response message. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function sendInvoiceResponseAsyncWithHttpInfo($party_id, $document_id, $invoice_response)
    {
        $returnType = '\EConnect\Psb\Model\Document';
        $request = $this->sendInvoiceResponseRequest($party_id, $document_id, $invoice_response);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->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 ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'sendInvoiceResponse'
     *
     * @param  string $party_id Your partyId (buyer). (required)
     * @param  string $document_id DocumentId that the response is about. (required)
     * @param  \EConnect\Psb\Model\InvoiceResponse $invoice_response Invoice response message. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function sendInvoiceResponseRequest($party_id, $document_id, $invoice_response)
    {
        // verify the required parameter 'party_id' is set
        if ($party_id === null || (is_array($party_id) && count($party_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $party_id when calling sendInvoiceResponse'
            );
        }
        if (!preg_match("/[A-Za-z0-9-=:]+/", $party_id)) {
            throw new \InvalidArgumentException("invalid value for \"party_id\" when calling PurchaseInvoiceApi.sendInvoiceResponse, must conform to the pattern /[A-Za-z0-9-=:]+/.");
        }

        // verify the required parameter 'document_id' is set
        if ($document_id === null || (is_array($document_id) && count($document_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $document_id when calling sendInvoiceResponse'
            );
        }
        if (strlen($document_id) > 256) {
            throw new \InvalidArgumentException('invalid length for "$document_id" when calling PurchaseInvoiceApi.sendInvoiceResponse, must be smaller than or equal to 256.');
        }

        // verify the required parameter 'invoice_response' is set
        if ($invoice_response === null || (is_array($invoice_response) && count($invoice_response) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $invoice_response when calling sendInvoiceResponse'
            );
        }

        $resourcePath = '/api/v1/{partyId}/purchaseInvoice/{documentId}/response';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($party_id !== null) {
            $resourcePath = str_replace(
                '{' . 'partyId' . '}',
                ObjectSerializer::toPathValue($party_id),
                $resourcePath
            );
        }
        // path params
        if ($document_id !== null) {
            $resourcePath = str_replace(
                '{' . 'documentId' . '}',
                ObjectSerializer::toPathValue($document_id),
                $resourcePath
            );
        }


        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                ['application/json']
            );
        }

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

            } else {
                // for HTTP post (form)
                $httpBody = \GuzzleHttp\Psr7\build_query($formParams);
            }
        }

        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }
        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('Subscription-Key');
        if ($apiKey !== null) {
            $headers['Subscription-Key'] = $apiKey;
        }

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

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

        $query = \GuzzleHttp\Psr7\build_query($queryParams);
        return new Request(
            'POST',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Create http client option
     *
     * @throws \RuntimeException on file opening failure
     * @return array of http client options
     */
    protected function createHttpClientOption()
    {
        $options = [];
        if ($this->config->getDebug()) {
            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
            if (!$options[RequestOptions::DEBUG]) {
                throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
            }
        }

        return $options;
    }
}
