<?php
/**
 * FilesImagesApi
 * PHP version 7.4
 *
 * @category Class
 * @package  SeaTable\Client
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * File Operations
 *
 * The official SeaTable API Reference (OpenAPI 3.0).
 *
 * The version of the OpenAPI document: 5.0
 * Generated by: https://openapi-generator.tech
 */

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

namespace SeaTable\Client\File;

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

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

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

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

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

    /** @var string[] $contentTypes **/
    public const contentTypes = [
        'getFileDownloadLink' => [
            'application/json',
        ],
        'getUploadLink' => [
            'application/json',
        ],
        'uploadFile' => [
            'multipart/form-data',
        ],
    ];

    /**
     * @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 getFileDownloadLink
     *
     * Get File Download Link
     *
     * @param  string $path Path to the file (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getFileDownloadLink'] to see the possible values for this operation
     *
     * @throws \SeaTable\Client\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return object
     */
    public function getFileDownloadLink($path, string $contentType = self::contentTypes['getFileDownloadLink'][0])
    {
        list($response) = $this->getFileDownloadLinkWithHttpInfo($path, $contentType);
        return $response;
    }

    /**
     * Operation getFileDownloadLinkWithHttpInfo
     *
     * Get File Download Link
     *
     * @param  string $path Path to the file (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getFileDownloadLink'] to see the possible values for this operation
     *
     * @throws \SeaTable\Client\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of object, HTTP status code, HTTP response headers (array of strings)
     */
    public function getFileDownloadLinkWithHttpInfo($path, string $contentType = self::contentTypes['getFileDownloadLink'][0])
    {
        $request = $this->getFileDownloadLinkRequest($path, $contentType);

        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
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    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 ('object' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('object' !== 'string') {
                            try {
                                $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                            } catch (\JsonException $exception) {
                                throw new ApiException(
                                    sprintf(
                                        'Error JSON decoding server response (%s)',
                                        $request->getUri()
                                    ),
                                    $statusCode,
                                    $response->getHeaders(),
                                    $content
                                );
                            }
                        }
                    }

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

            $returnType = 'object';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    try {
                        $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                    } catch (\JsonException $exception) {
                        throw new ApiException(
                            sprintf(
                                'Error JSON decoding server response (%s)',
                                $request->getUri()
                            ),
                            $statusCode,
                            $response->getHeaders(),
                            $content
                        );
                    }
                }
            }

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

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'object',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation getFileDownloadLinkAsync
     *
     * Get File Download Link
     *
     * @param  string $path Path to the file (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getFileDownloadLink'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getFileDownloadLinkAsync($path, string $contentType = self::contentTypes['getFileDownloadLink'][0])
    {
        return $this->getFileDownloadLinkAsyncWithHttpInfo($path, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getFileDownloadLinkAsyncWithHttpInfo
     *
     * Get File Download Link
     *
     * @param  string $path Path to the file (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getFileDownloadLink'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getFileDownloadLinkAsyncWithHttpInfo($path, string $contentType = self::contentTypes['getFileDownloadLink'][0])
    {
        $returnType = 'object';
        $request = $this->getFileDownloadLinkRequest($path, $contentType);

        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();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    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 'getFileDownloadLink'
     *
     * @param  string $path Path to the file (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getFileDownloadLink'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getFileDownloadLinkRequest($path, string $contentType = self::contentTypes['getFileDownloadLink'][0])
    {

        // verify the required parameter 'path' is set
        if ($path === null || (is_array($path) && count($path) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $path when calling getFileDownloadLink'
            );
        }
        if (!preg_match("/^\/(images|files){1}\/[0-9]{4}\\-[0-9]{2}\/./", $path)) {
            throw new \InvalidArgumentException("invalid value for \"path\" when calling FilesImagesApi.getFileDownloadLink, must conform to the pattern /^\/(images|files){1}\/[0-9]{4}\\-[0-9]{2}\/./.");
        }
        

        $resourcePath = '/api/v2.1/dtable/app-download-link/';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $path,
            'path', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            true // required
        ) ?? []);




        if ($contentType === 'multipart/form-data') {
            $multipart = true;
        }

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

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

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

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

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

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'GET',
            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation getUploadLink
     *
     * Get Upload Link
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getUploadLink'] to see the possible values for this operation
     *
     * @throws \SeaTable\Client\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return object
     */
    public function getUploadLink(string $contentType = self::contentTypes['getUploadLink'][0])
    {
        list($response) = $this->getUploadLinkWithHttpInfo($contentType);
        return $response;
    }

    /**
     * Operation getUploadLinkWithHttpInfo
     *
     * Get Upload Link
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getUploadLink'] to see the possible values for this operation
     *
     * @throws \SeaTable\Client\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of object, HTTP status code, HTTP response headers (array of strings)
     */
    public function getUploadLinkWithHttpInfo(string $contentType = self::contentTypes['getUploadLink'][0])
    {
        $request = $this->getUploadLinkRequest($contentType);

        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
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    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 ('object' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('object' !== 'string') {
                            try {
                                $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                            } catch (\JsonException $exception) {
                                throw new ApiException(
                                    sprintf(
                                        'Error JSON decoding server response (%s)',
                                        $request->getUri()
                                    ),
                                    $statusCode,
                                    $response->getHeaders(),
                                    $content
                                );
                            }
                        }
                    }

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

            $returnType = 'object';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    try {
                        $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                    } catch (\JsonException $exception) {
                        throw new ApiException(
                            sprintf(
                                'Error JSON decoding server response (%s)',
                                $request->getUri()
                            ),
                            $statusCode,
                            $response->getHeaders(),
                            $content
                        );
                    }
                }
            }

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

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'object',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation getUploadLinkAsync
     *
     * Get Upload Link
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getUploadLink'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getUploadLinkAsync(string $contentType = self::contentTypes['getUploadLink'][0])
    {
        return $this->getUploadLinkAsyncWithHttpInfo($contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getUploadLinkAsyncWithHttpInfo
     *
     * Get Upload Link
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getUploadLink'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getUploadLinkAsyncWithHttpInfo(string $contentType = self::contentTypes['getUploadLink'][0])
    {
        $returnType = 'object';
        $request = $this->getUploadLinkRequest($contentType);

        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();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    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 'getUploadLink'
     *
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getUploadLink'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getUploadLinkRequest(string $contentType = self::contentTypes['getUploadLink'][0])
    {


        $resourcePath = '/api/v2.1/dtable/app-upload-link/';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;





        if ($contentType === 'multipart/form-data') {
            $multipart = true;
        }

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

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

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

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

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

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'GET',
            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation uploadFile
     *
     * Upload File (or Image)
     *
     * @param  string $upload_link This is the value you got from the call Get File/Image Upload Link via API Token. (required)
     * @param  \SplFileObject $file The file or image you&#39;d like to upload from your local drive. (required)
     * @param  string $parent_dir This is the value of the &#x60;parent_path&#x60; you got from the call **Get File/Image Upload Link via API Token**. (required)
     * @param  string $relative_path If you are uploading a file, use the value of the &#x60;file_relative_path&#x60; returned in the call **Get File/Image Upload Link via API Token**; or the &#x60;img_relative_path&#x60; for image. (required)
     * @param  string $replace Do you want to overwrite a file/image with the same name? &#x60;0&#x60; - No, &#x60;1&#x60; - Yes. Optional. &#x60;0&#x60; by default. If existing file is not overwritten, the uploaded file will be renamed as &#x60;filename(1).xxx&#x60;. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation
     *
     * @throws \SeaTable\Client\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return object[]
     */
    public function uploadFile($upload_link, $file, $parent_dir, $relative_path, $replace = null, string $contentType = self::contentTypes['uploadFile'][0])
    {
        list($response) = $this->uploadFileWithHttpInfo($upload_link, $file, $parent_dir, $relative_path, $replace, $contentType);
        return $response;
    }

    /**
     * Operation uploadFileWithHttpInfo
     *
     * Upload File (or Image)
     *
     * @param  string $upload_link This is the value you got from the call Get File/Image Upload Link via API Token. (required)
     * @param  \SplFileObject $file The file or image you&#39;d like to upload from your local drive. (required)
     * @param  string $parent_dir This is the value of the &#x60;parent_path&#x60; you got from the call **Get File/Image Upload Link via API Token**. (required)
     * @param  string $relative_path If you are uploading a file, use the value of the &#x60;file_relative_path&#x60; returned in the call **Get File/Image Upload Link via API Token**; or the &#x60;img_relative_path&#x60; for image. (required)
     * @param  string $replace Do you want to overwrite a file/image with the same name? &#x60;0&#x60; - No, &#x60;1&#x60; - Yes. Optional. &#x60;0&#x60; by default. If existing file is not overwritten, the uploaded file will be renamed as &#x60;filename(1).xxx&#x60;. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation
     *
     * @throws \SeaTable\Client\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of object[], HTTP status code, HTTP response headers (array of strings)
     */
    public function uploadFileWithHttpInfo($upload_link, $file, $parent_dir, $relative_path, $replace = null, string $contentType = self::contentTypes['uploadFile'][0])
    {
        $request = $this->uploadFileRequest($upload_link, $file, $parent_dir, $relative_path, $replace, $contentType);

        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
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    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 ('object[]' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('object[]' !== 'string') {
                            try {
                                $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                            } catch (\JsonException $exception) {
                                throw new ApiException(
                                    sprintf(
                                        'Error JSON decoding server response (%s)',
                                        $request->getUri()
                                    ),
                                    $statusCode,
                                    $response->getHeaders(),
                                    $content
                                );
                            }
                        }
                    }

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

            $returnType = 'object[]';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    try {
                        $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                    } catch (\JsonException $exception) {
                        throw new ApiException(
                            sprintf(
                                'Error JSON decoding server response (%s)',
                                $request->getUri()
                            ),
                            $statusCode,
                            $response->getHeaders(),
                            $content
                        );
                    }
                }
            }

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

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        'object[]',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation uploadFileAsync
     *
     * Upload File (or Image)
     *
     * @param  string $upload_link This is the value you got from the call Get File/Image Upload Link via API Token. (required)
     * @param  \SplFileObject $file The file or image you&#39;d like to upload from your local drive. (required)
     * @param  string $parent_dir This is the value of the &#x60;parent_path&#x60; you got from the call **Get File/Image Upload Link via API Token**. (required)
     * @param  string $relative_path If you are uploading a file, use the value of the &#x60;file_relative_path&#x60; returned in the call **Get File/Image Upload Link via API Token**; or the &#x60;img_relative_path&#x60; for image. (required)
     * @param  string $replace Do you want to overwrite a file/image with the same name? &#x60;0&#x60; - No, &#x60;1&#x60; - Yes. Optional. &#x60;0&#x60; by default. If existing file is not overwritten, the uploaded file will be renamed as &#x60;filename(1).xxx&#x60;. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function uploadFileAsync($upload_link, $file, $parent_dir, $relative_path, $replace = null, string $contentType = self::contentTypes['uploadFile'][0])
    {
        return $this->uploadFileAsyncWithHttpInfo($upload_link, $file, $parent_dir, $relative_path, $replace, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation uploadFileAsyncWithHttpInfo
     *
     * Upload File (or Image)
     *
     * @param  string $upload_link This is the value you got from the call Get File/Image Upload Link via API Token. (required)
     * @param  \SplFileObject $file The file or image you&#39;d like to upload from your local drive. (required)
     * @param  string $parent_dir This is the value of the &#x60;parent_path&#x60; you got from the call **Get File/Image Upload Link via API Token**. (required)
     * @param  string $relative_path If you are uploading a file, use the value of the &#x60;file_relative_path&#x60; returned in the call **Get File/Image Upload Link via API Token**; or the &#x60;img_relative_path&#x60; for image. (required)
     * @param  string $replace Do you want to overwrite a file/image with the same name? &#x60;0&#x60; - No, &#x60;1&#x60; - Yes. Optional. &#x60;0&#x60; by default. If existing file is not overwritten, the uploaded file will be renamed as &#x60;filename(1).xxx&#x60;. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function uploadFileAsyncWithHttpInfo($upload_link, $file, $parent_dir, $relative_path, $replace = null, string $contentType = self::contentTypes['uploadFile'][0])
    {
        $returnType = 'object[]';
        $request = $this->uploadFileRequest($upload_link, $file, $parent_dir, $relative_path, $replace, $contentType);

        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();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    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 'uploadFile'
     *
     * @param  string $upload_link This is the value you got from the call Get File/Image Upload Link via API Token. (required)
     * @param  \SplFileObject $file The file or image you&#39;d like to upload from your local drive. (required)
     * @param  string $parent_dir This is the value of the &#x60;parent_path&#x60; you got from the call **Get File/Image Upload Link via API Token**. (required)
     * @param  string $relative_path If you are uploading a file, use the value of the &#x60;file_relative_path&#x60; returned in the call **Get File/Image Upload Link via API Token**; or the &#x60;img_relative_path&#x60; for image. (required)
     * @param  string $replace Do you want to overwrite a file/image with the same name? &#x60;0&#x60; - No, &#x60;1&#x60; - Yes. Optional. &#x60;0&#x60; by default. If existing file is not overwritten, the uploaded file will be renamed as &#x60;filename(1).xxx&#x60;. (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function uploadFileRequest($upload_link, $file, $parent_dir, $relative_path, $replace = null, string $contentType = self::contentTypes['uploadFile'][0])
    {

        // verify the required parameter 'upload_link' is set
        if ($upload_link === null || (is_array($upload_link) && count($upload_link) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $upload_link when calling uploadFile'
            );
        }
        if (!preg_match("/^[a-z0-9]{8}(-[a-z0-9]{4}){3}-[a-z0-9]{12}$/", $upload_link)) {
            throw new \InvalidArgumentException("invalid value for \"upload_link\" when calling FilesImagesApi.uploadFile, must conform to the pattern /^[a-z0-9]{8}(-[a-z0-9]{4}){3}-[a-z0-9]{12}$/.");
        }
        
        // 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 uploadFile'
            );
        }

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

        // verify the required parameter 'relative_path' is set
        if ($relative_path === null || (is_array($relative_path) && count($relative_path) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $relative_path when calling uploadFile'
            );
        }
        if (!preg_match("/^(images|files){1}\/[0-9]{4}\\-[0-9]{2}$/", $relative_path)) {
            throw new \InvalidArgumentException("invalid value for \"relative_path\" when calling FilesImagesApi.uploadFile, must conform to the pattern /^(images|files){1}\/[0-9]{4}\\-[0-9]{2}$/.");
        }
        


        $resourcePath = '/seafhttp/upload-api/{upload_link}?ret-json=1';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



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

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

        if ($contentType === 'multipart/form-data') {
            $multipart = true;
        }

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

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

            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }

        // this endpoint requires Bearer authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

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

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

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'POST',
            $operationHost . $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;
    }
}
