# coding: utf-8

# -----------------------------------------------------------------------------------
# <copyright company="Aspose">
#   Copyright (c) 2018 Aspose.Slides for Cloud
# </copyright>
# <summary>
#   Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in all
#  copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#  SOFTWARE.
# </summary>
# -----------------------------------------------------------------------------------

from __future__ import absolute_import

import io
import json
import ssl
import sys
import certifi
import logging
import re

# python 2 and python 3 compatibility library
from six import PY3
from six.moves.urllib.parse import urlencode

try:
    import urllib3
except ImportError:
    raise ImportError('Swagger python client requires urllib3.')

logger = logging.getLogger(__name__)

class RESTResponse(io.IOBase):

    def __init__(self, resp):
        self.urllib3_response = resp
        self.status = resp.status
        self.reason = resp.reason
        self.data = resp.data

    def getheaders(self):
        """
        Returns a dictionary of the response headers.
        """
        return self.urllib3_response.getheaders()

    def getheader(self, name, default=None):
        """
        Returns a given response header.
        """
        return self.urllib3_response.getheader(name, default)


class RESTClientObject(object):

    def __init__(self, configuration, pools_size=4, maxsize=4):
        # urllib3.PoolManager will pass all kw parameters to connectionpool
        # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75
        # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680
        # maxsize is the number of requests to host that are allowed in parallel
        # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html

        if configuration.debug:
            logger.setLevel(logging.DEBUG)

        # cert_reqs
        if configuration.verify_ssl:
            cert_reqs = ssl.CERT_REQUIRED
        else:
            urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
            cert_reqs = ssl.CERT_NONE

        # ca_certs
        if configuration.ssl_ca_cert:
            ca_certs = configuration.ssl_ca_cert
        else:
            # if not set certificate file, use Mozilla's root certificates.
            ca_certs = certifi.where()

        # https pool manager
        if configuration.proxy:
            self.pool_manager = urllib3.ProxyManager(
                num_pools=pools_size,
                maxsize=maxsize,
                cert_reqs=cert_reqs,
                ca_certs=ca_certs,
                cert_file=configuration.cert_file,
                key_file=configuration.key_file,
                proxy_url=configuration.proxy
            )
        else:
            self.pool_manager = urllib3.PoolManager(
                num_pools=pools_size,
                maxsize=maxsize,
                cert_reqs=cert_reqs,
                ca_certs=ca_certs,
                cert_file=configuration.cert_file,
                key_file=configuration.key_file
            )

    def request(self, method, url, query_params=None, headers=None,
                body=None, post_params=None, files=None, _preload_content=True, _request_timeout=None):
        """
        :param method: http request method
        :param url: http request url
        :param query_params: query parameters in the url
        :param headers: http request headers
        :param body: request json body, for `application/json`
        :param post_params: request post parameters,
                            `application/x-www-form-urlencoded`
                            and `multipart/form-data`
        :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without
                                 reading/decoding response data. Default is True.
        :param _request_timeout: timeout setting for this request. If one number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of (connection, read) timeouts.
        """
        method = method.upper()
        assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS']
        headers = headers or {}

        timeout = None
        if _request_timeout:
            if isinstance(_request_timeout, (int, ) if PY3 else (int, long)):
                timeout = urllib3.Timeout(total=_request_timeout)
            elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2:
                timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1])

        part_count = 0
        if files:
            if not body is None:
                part_count = 1
            part_count = part_count + len(files)
        if part_count > 0:
            headers['Content-Type'] = 'multipart/form-data'
        if 'Content-Type' not in headers:
            headers['Content-Type'] = 'application/json'

        logger.debug('>> ' + method + ' ' + url)
        if query_params:
            logger.debug('Query: ' + json.dumps(query_params))
        if post_params:
            logger.debug('Post parameters: %s', post_params)
        if headers:
            logger.debug('Headers: ' + json.dumps(headers))
        if not body is None and headers['Content-Type'] != 'multipart/form-data':
            logger.debug("Body: %s", body)
        try:
            # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
            if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
                if query_params:
                    url += '?' + urlencode(query_params)
                if post_params and len(post_params) > 0:
                    headers['Content-Type'] = 'application/x-www-form-urlencoded'
                    r = self.pool_manager.request(method, url,
                                                  fields=post_params,
                                                  encode_multipart=False,
                                                  preload_content=_preload_content,
                                                  timeout=timeout,
                                                  headers=headers)
                elif part_count > 0:
                    del headers['Content-Type']
                    file_params = {}
                    if not body is None:
                        body = self.getBytes(body)
                        if not isinstance(body, bytes):
                            body = json.dumps(body)
                        file_params["pipeline"] = (None, body, "text/json")
                    if not files is None:
                        if type(files) is list:
                            for index, item in enumerate(files):
                                if type(item) == tuple:
                                    file_params[item[0]] = (item[0], self.getBytes(item[1]))
                                else:
                                    file_params["file" + str(index + 1)] = ("file" + str(index + 1), self.getBytes(item))
                        else:
                            for file_key in files:
                                if type(files[file_key]) == tuple:
                                    file_params[file_key] = (files[file_key][0], self.getBytes(files[file_key][1]))
                                else:
                                    file_params[file_key] = (file_key, self.getBytes(files[file_key]))
                    r = self.pool_manager.request(method, url,
                                              fields=file_params,
                                              encode_multipart=True,
                                              preload_content=_preload_content,
                                              timeout=timeout,
                                              headers=headers)
                elif not body is None:
                    request_body = None
                    if isinstance(body, bytes) or isinstance(body, str):
                        headers['Content-Type'] = 'application/octet-stream'
                        request_body = body
                    else:
                        headers['Content-Type'] = 'application/json'
                        request_body = json.dumps(body)
                    r = self.pool_manager.request(method, url,
                                              body=request_body,
                                              preload_content=_preload_content,
                                              timeout=timeout,
                                              headers=headers)
                else:
                    del headers['Content-Type']
                    r = self.pool_manager.request(method, url,
                                              body=body,
                                              preload_content=_preload_content,
                                              timeout=timeout,
                                              headers=headers)
            # For `GET`, `HEAD`
            else:
                r = self.pool_manager.request(method, url,
                                              fields=query_params,
                                              preload_content=_preload_content,
                                              timeout=timeout,
                                              headers=headers)
        except urllib3.exceptions.SSLError as e:
            msg = "{0}\n{1}".format(type(e).__name__, str(e))
            raise ApiException(status=0, reason=msg)

        logger.debug('<< ' + str(r.status))
        if _preload_content:
            r = RESTResponse(r)
        
        response_type = ''
        if 'Content-Type' in r.getheaders():
            response_type = r.getheaders()['Content-Type']

        if 'text' in response_type or 'json' in response_type:
            logger.debug("response body: %s", r.data)
        elif r.data:
            logger.debug("response body: binary (%s bytes)", len(r.data))

        if not 200 <= r.status <= 299:
            raise ApiException(http_resp=r)

        return r

    def getBytes(self, data):
        read_op = getattr(data, 'read', None)
        if callable(read_op):
            return data.read()
        return data

    def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None):
        return self.request("GET", url,
                            headers=headers,
                            _preload_content=_preload_content,
                            _request_timeout=_request_timeout,
                            query_params=query_params)

    def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None):
        return self.request("HEAD", url,
                            headers=headers,
                            _preload_content=_preload_content,
                            _request_timeout=_request_timeout,
                            query_params=query_params)

    def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, files=None, _preload_content=True,
                _request_timeout=None):
        return self.request("OPTIONS", url,
                            headers=headers,
                            query_params=query_params,
                            post_params=post_params,
                            files=files,
                            _preload_content=_preload_content,
                            _request_timeout=_request_timeout,
                            body=body)

    def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None):
        return self.request("DELETE", url,
                            headers=headers,
                            query_params=query_params,
                            _preload_content=_preload_content,
                            _request_timeout=_request_timeout,
                            body=body)

    def POST(self, url, headers=None, query_params=None, post_params=None, body=None, files=None, _preload_content=True,
             _request_timeout=None):
        return self.request("POST", url,
                            headers=headers,
                            query_params=query_params,
                            post_params=post_params,
                            files=files,
                            _preload_content=_preload_content,
                            _request_timeout=_request_timeout,
                            body=body)

    def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, files=None, _preload_content=True,
            _request_timeout=None):
        return self.request("PUT", url,
                            headers=headers,
                            query_params=query_params,
                            post_params=post_params,
                            files=files,
                            _preload_content=_preload_content,
                            _request_timeout=_request_timeout,
                            body=body)

    def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, files=None, _preload_content=True,
              _request_timeout=None):
        return self.request("PATCH", url,
                            headers=headers,
                            query_params=query_params,
                            post_params=post_params,
                            files=files,
                            _preload_content=_preload_content,
                            _request_timeout=_request_timeout,
                            body=body)


class ApiException(Exception):

    def __init__(self, status=None, reason=None, http_resp=None):
        if http_resp:
            self.status = http_resp.status
            self.reason = http_resp.reason
            try:
                self.body = http_resp.data
            except:
                self.body = None
            self.headers = http_resp.getheaders()
        else:
            self.status = status
            self.reason = reason
            self.body = None
            self.headers = None

    def __str__(self):
        """
        Custom error messages for exception
        """
        error_message = "({0})\n"\
                        "Reason: {1}\n".format(self.status, self.reason)
        if self.headers:
            error_message += "HTTP response headers: {0}\n".format(self.headers)

        if self.body:
            error_message += "HTTP response body: {0}\n".format(self.body)

        return error_message