<?php
/**
 * SalesInvoiceApi
 * 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;

/**
 * SalesInvoiceApi Class Doc Comment
 *
 * @category Class
 * @package  EConnect\Psb
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */
class SalesInvoiceApi
{
    /**
     * @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 getSalesInvoiceStatuses
     *
     * Get sales invoice statuses.
     *
     * @param  string $party_id The sender 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 getSalesInvoiceStatuses($party_id, $document_id)
    {
        list($response) = $this->getSalesInvoiceStatusesWithHttpInfo($party_id, $document_id);
        return $response;
    }

    /**
     * Operation getSalesInvoiceStatusesWithHttpInfo
     *
     * Get sales invoice statuses.
     *
     * @param  string $party_id The sender 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 getSalesInvoiceStatusesWithHttpInfo($party_id, $document_id)
    {
        $request = $this->getSalesInvoiceStatusesRequest($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 getSalesInvoiceStatusesAsync
     *
     * Get sales invoice statuses.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getSalesInvoiceStatusesAsync($party_id, $document_id)
    {
        return $this->getSalesInvoiceStatusesAsyncWithHttpInfo($party_id, $document_id)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getSalesInvoiceStatusesAsyncWithHttpInfo
     *
     * Get sales invoice statuses.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getSalesInvoiceStatusesAsyncWithHttpInfo($party_id, $document_id)
    {
        $returnType = '\EConnect\Psb\Model\DocumentStatus[]';
        $request = $this->getSalesInvoiceStatusesRequest($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 'getSalesInvoiceStatuses'
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  string $document_id The service bus documentId. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getSalesInvoiceStatusesRequest($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 getSalesInvoiceStatuses'
            );
        }
        if (!preg_match("/[A-Za-z0-9-=:]+/", $party_id)) {
            throw new \InvalidArgumentException("invalid value for \"party_id\" when calling SalesInvoiceApi.getSalesInvoiceStatuses, 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 getSalesInvoiceStatuses'
            );
        }
        if (strlen($document_id) > 256) {
            throw new \InvalidArgumentException('invalid length for "$document_id" when calling SalesInvoiceApi.getSalesInvoiceStatuses, must be smaller than or equal to 256.');
        }


        $resourcePath = '/api/v1/{partyId}/salesInvoice/{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 queryRecipientPartyForSalesInvoice
     *
     * Lookup the recipient party in Peppol.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  string[] $request_body All possible partyIds of the recipient party (required)
     * @param  string $preferred_document_type_id The source or preferred documentTypeId to match with and to determine the partyId format. (optional)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \EConnect\Psb\Model\Party
     */
    public function queryRecipientPartyForSalesInvoice($party_id, $request_body, $preferred_document_type_id = null)
    {
        list($response) = $this->queryRecipientPartyForSalesInvoiceWithHttpInfo($party_id, $request_body, $preferred_document_type_id);
        return $response;
    }

    /**
     * Operation queryRecipientPartyForSalesInvoiceWithHttpInfo
     *
     * Lookup the recipient party in Peppol.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  string[] $request_body All possible partyIds of the recipient party (required)
     * @param  string $preferred_document_type_id The source or preferred documentTypeId to match with and to determine the partyId format. (optional)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \EConnect\Psb\Model\Party, HTTP status code, HTTP response headers (array of strings)
     */
    public function queryRecipientPartyForSalesInvoiceWithHttpInfo($party_id, $request_body, $preferred_document_type_id = null)
    {
        $request = $this->queryRecipientPartyForSalesInvoiceRequest($party_id, $request_body, $preferred_document_type_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\Party' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

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

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

    /**
     * Operation queryRecipientPartyForSalesInvoiceAsync
     *
     * Lookup the recipient party in Peppol.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  string[] $request_body All possible partyIds of the recipient party (required)
     * @param  string $preferred_document_type_id The source or preferred documentTypeId to match with and to determine the partyId format. (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function queryRecipientPartyForSalesInvoiceAsync($party_id, $request_body, $preferred_document_type_id = null)
    {
        return $this->queryRecipientPartyForSalesInvoiceAsyncWithHttpInfo($party_id, $request_body, $preferred_document_type_id)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation queryRecipientPartyForSalesInvoiceAsyncWithHttpInfo
     *
     * Lookup the recipient party in Peppol.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  string[] $request_body All possible partyIds of the recipient party (required)
     * @param  string $preferred_document_type_id The source or preferred documentTypeId to match with and to determine the partyId format. (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function queryRecipientPartyForSalesInvoiceAsyncWithHttpInfo($party_id, $request_body, $preferred_document_type_id = null)
    {
        $returnType = '\EConnect\Psb\Model\Party';
        $request = $this->queryRecipientPartyForSalesInvoiceRequest($party_id, $request_body, $preferred_document_type_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 'queryRecipientPartyForSalesInvoice'
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  string[] $request_body All possible partyIds of the recipient party (required)
     * @param  string $preferred_document_type_id The source or preferred documentTypeId to match with and to determine the partyId format. (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function queryRecipientPartyForSalesInvoiceRequest($party_id, $request_body, $preferred_document_type_id = 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 queryRecipientPartyForSalesInvoice'
            );
        }
        if (!preg_match("/[A-Za-z0-9-=:]+/", $party_id)) {
            throw new \InvalidArgumentException("invalid value for \"party_id\" when calling SalesInvoiceApi.queryRecipientPartyForSalesInvoice, must conform to the pattern /[A-Za-z0-9-=:]+/.");
        }

        // verify the required parameter 'request_body' is set
        if ($request_body === null || (is_array($request_body) && count($request_body) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $request_body when calling queryRecipientPartyForSalesInvoice'
            );
        }
        if ($preferred_document_type_id !== null && !preg_match("/[A-Za-z0-9-:.]{1,}[#]{2}[A-Za-z0-9-:.#*]{1,}|^$/", $preferred_document_type_id)) {
            throw new \InvalidArgumentException("invalid value for \"preferred_document_type_id\" when calling SalesInvoiceApi.queryRecipientPartyForSalesInvoice, must conform to the pattern /[A-Za-z0-9-:.]{1,}[#]{2}[A-Za-z0-9-:.#*]{1,}|^$/.");
        }


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

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


        // path params
        if ($party_id !== null) {
            $resourcePath = str_replace(
                '{' . 'partyId' . '}',
                ObjectSerializer::toPathValue($party_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($request_body)) {
            if ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($request_body));
            } else {
                $httpBody = $request_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 = \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 recognizeSalesInvoice
     *
     * Recognize sales invoice.
     *
     * @param  string $party_id The sender partyId (required)
     * @param  \SplFileObject $file file (required)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return |\EConnect\Psb\Model\Document
     */
    public function recognizeSalesInvoice($party_id, $file)
    {
        list($response) = $this->recognizeSalesInvoiceWithHttpInfo($party_id, $file);
        return $response;
    }

    /**
     * Operation recognizeSalesInvoiceWithHttpInfo
     *
     * Recognize sales invoice.
     *
     * @param  string $party_id The sender 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 recognizeSalesInvoiceWithHttpInfo($party_id, $file)
    {
        $request = $this->recognizeSalesInvoiceRequest($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 recognizeSalesInvoiceAsync
     *
     * Recognize sales invoice.
     *
     * @param  string $party_id The sender partyId (required)
     * @param  \SplFileObject $file (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function recognizeSalesInvoiceAsync($party_id, $file)
    {
        return $this->recognizeSalesInvoiceAsyncWithHttpInfo($party_id, $file)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation recognizeSalesInvoiceAsyncWithHttpInfo
     *
     * Recognize sales invoice.
     *
     * @param  string $party_id The sender partyId (required)
     * @param  \SplFileObject $file (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function recognizeSalesInvoiceAsyncWithHttpInfo($party_id, $file)
    {
        $returnType = '\EConnect\Psb\Model\Document';
        $request = $this->recognizeSalesInvoiceRequest($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 'recognizeSalesInvoice'
     *
     * @param  string $party_id The sender partyId (required)
     * @param  \SplFileObject $file (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function recognizeSalesInvoiceRequest($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 recognizeSalesInvoice'
            );
        }
        if (!preg_match("/[A-Za-z0-9-=:]+/", $party_id)) {
            throw new \InvalidArgumentException("invalid value for \"party_id\" when calling SalesInvoiceApi.recognizeSalesInvoice, 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 recognizeSalesInvoice'
            );
        }

        $resourcePath = '/api/v1/{partyId}/salesInvoice/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 sendSalesInvoice
     *
     * Send an invoice.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  \SplFileObject $file file (required)
     * @param  string $receiver_id An optional receiver partyId to enforce delivery to a specific endpoint. The receiverId will be injected into the document. (optional)
     *
     * @throws \EConnect\Psb\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return |\EConnect\Psb\Model\Document
     */
    public function sendSalesInvoice($party_id, $file, $receiver_id = null)
    {
        list($response) = $this->sendSalesInvoiceWithHttpInfo($party_id, $file, $receiver_id);
        return $response;
    }

    /**
     * Operation sendSalesInvoiceWithHttpInfo
     *
     * Send an invoice.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  \SplFileObject $file (required)
     * @param  string $receiver_id An optional receiver partyId to enforce delivery to a specific endpoint. The receiverId will be injected into the document. (optional)
     *
     * @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 sendSalesInvoiceWithHttpInfo($party_id, $file, $receiver_id = null)
    {
        $request = $this->sendSalesInvoiceRequest($party_id, $file, $receiver_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\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 sendSalesInvoiceAsync
     *
     * Send an invoice.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  \SplFileObject $file (required)
     * @param  string $receiver_id An optional receiver partyId to enforce delivery to a specific endpoint. The receiverId will be injected into the document. (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function sendSalesInvoiceAsync($party_id, $file, $receiver_id = null)
    {
        return $this->sendSalesInvoiceAsyncWithHttpInfo($party_id, $file, $receiver_id)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation sendSalesInvoiceAsyncWithHttpInfo
     *
     * Send an invoice.
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  \SplFileObject $file (required)
     * @param  string $receiver_id An optional receiver partyId to enforce delivery to a specific endpoint. The receiverId will be injected into the document. (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function sendSalesInvoiceAsyncWithHttpInfo($party_id, $file, $receiver_id = null)
    {
        $returnType = '\EConnect\Psb\Model\Document';
        $request = $this->sendSalesInvoiceRequest($party_id, $file, $receiver_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 'sendSalesInvoice'
     *
     * @param  string $party_id The sender partyId. (required)
     * @param  \SplFileObject $file (required)
     * @param  string $receiver_id An optional receiver partyId to enforce delivery to a specific endpoint. The receiverId will be injected into the document. (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function sendSalesInvoiceRequest($party_id, $file, $receiver_id = 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 sendSalesInvoice'
            );
        }
        if (!preg_match("/[A-Za-z0-9-=:]+/", $party_id)) {
            throw new \InvalidArgumentException("invalid value for \"party_id\" when calling SalesInvoiceApi.sendSalesInvoice, 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 sendSalesInvoice'
            );
        }
        if ($receiver_id !== null && !preg_match("/[A-Za-z0-9-=:]+/", $receiver_id)) {
            throw new \InvalidArgumentException("invalid value for \"receiver_id\" when calling SalesInvoiceApi.sendSalesInvoice, must conform to the pattern /[A-Za-z0-9-=:]+/.");
        }


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

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


        // 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
        );
    }

    /**
     * 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;
    }
}
