# coding: utf-8


"""
IGNORE:
    Nutanix Flow Management APIs

    Manage Network Security Policy configuration of Nutanix clusters.  # noqa: E501

    OpenAPI spec version: 4.2.1
    
    Generated by: https://github.com/swagger-api/swagger-codegen.git
IGNORE
"""
from __future__ import absolute_import

import io
import json
import logging
import re
import ssl

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

try:
    import urllib3
    from urllib3.contrib.socks import SOCKSProxyManager
except ImportError:
    raise ImportError('Swagger python client requires urllib3.')

from .custom_retry import CustomPoolManager

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 = None

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

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


class RESTClientObject(object):

    # Allowed methods to be used for retry
    RETRY_ALLOWED_METHODS = frozenset(["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE", "POST"])

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

        self.__configuration = configuration

        # cert_reqs
        if configuration.verify_ssl:
            cert_reqs = ssl.CERT_REQUIRED
        else:
            cert_reqs = ssl.CERT_NONE

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

        addition_pool_args = {}
        if configuration.assert_hostname is not None:
            addition_pool_args['assert_hostname'] = configuration.assert_hostname  # noqa: E501

        if maxsize is None:
            if configuration.connection_pool_maxsize is not None:
                maxsize = configuration.connection_pool_maxsize
            else:
                maxsize = 4

        # retry mechanism
        retries = urllib3.util.Retry(total=None, status=max_retry_attempts, read=0, connect=0, other=0, allowed_methods= self.RETRY_ALLOWED_METHODS, status_forcelist=[408, 429, 503, 504], backoff_factor=backoff_factor, raise_on_status=False, redirect=False)

        # https pool manager
        if configuration.proxy_scheme and configuration.proxy_host and configuration.proxy_port:
            proxy_url = ''.join([
                configuration.proxy_scheme,
                '://',
                configuration.proxy_host,
                ':',
                str(configuration.proxy_port)
            ])
            proxy_headers = (
                urllib3.util.make_headers(
                proxy_basic_auth=configuration.proxy_username + ':' + configuration.proxy_password) if
                (configuration.proxy_username and configuration.proxy_password) else None
            )
            if configuration.proxy_scheme == "socks5":
                self.pool_manager = SOCKSProxyManager(
                    num_pools=pools_size,
                    maxsize=maxsize,
                    cert_reqs=cert_reqs,
                    ca_certs=ca_certs,
                    cert_file=configuration.client_certificate_file,
                    key_file=configuration.client_key_file,
                    proxy_url=proxy_url,
                    username=configuration.proxy_username,
                    password=configuration.proxy_password,
                    retries = retries,
                    **addition_pool_args
                )
            else:
                self.pool_manager = urllib3.ProxyManager(
                    num_pools=pools_size,
                    maxsize=maxsize,
                    cert_reqs=cert_reqs,
                    ca_certs=ca_certs,
                    cert_file=configuration.client_certificate_file,
                    key_file=configuration.client_key_file,
                    proxy_url=proxy_url,
                    proxy_headers=proxy_headers,
                    retries = retries,
                    **addition_pool_args
                )
        else:
            self.pool_manager = CustomPoolManager(
                pools_size,
                maxsize,
                cert_reqs,
                ca_certs,
                configuration.client_certificate_file,
                configuration.client_key_file,
                retries,
                **addition_pool_args
            )

    def request(self, method, url, query_params=None, headers=None,
                body=None, post_params=None, _preload_content=True,
                _request_timeout=None):
        """Perform requests.

        :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']

        if post_params and body:
            msg = "body parameter cannot be used with post_params parameter."
            logger.error(msg)
            raise ValueError(msg)

        post_params = post_params or {}
        headers = headers or {}

        timeout = None
        if _request_timeout:
            if isinstance(_request_timeout, (int, float) if six.PY3 else (int, long, float)):  # noqa: E501,F821
                timeout = urllib3.Timeout(total=_request_timeout)
            elif (isinstance(_request_timeout, list) and len(_request_timeout) == 2):
                timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1])

        if 'Content-Type' not in headers:
            headers['Content-Type'] = 'application/json'

        _preload_content = False

        # Print log statements
        logger.info("%s %s", method, url + '?' + urlencode(query_params) if query_params else url)
        # Print debug logs, if enabled
        if self.__configuration.debug:
            logger.debug("Request Headers:")
            for key, value in six.iteritems(headers):
                logger.debug("%s: %s", key, value)

        try:
            # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
            if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
                if query_params:
                    url += '?' + urlencode(query_params)
                if re.search('json', headers['Content-Type'], re.IGNORECASE):
                    request_body = None
                    if body is not None:
                        request_body = json.dumps(body)

                    # Print request body, if debug configuration is enabled
                    if self.__configuration.debug:
                        logger.debug("Request Body: %s", request_body)

                    r = self.pool_manager.request(
                        method, url,
                        body=request_body,
                        preload_content=_preload_content,
                        timeout=timeout,
                        headers=headers)
                elif headers['Content-Type'] == 'application/x-www-form-urlencoded':  # noqa: E501
                    r = self.pool_manager.request(
                        method, url,
                        fields=post_params,
                        encode_multipart=False,
                        preload_content=_preload_content,
                        timeout=timeout,
                        headers=headers)
                elif headers['Content-Type'] == 'multipart/form-data':
                    # must del headers['Content-Type'], or the correct
                    # Content-Type which generated by urllib3 will be
                    # overwritten.
                    content_type_header = headers['Content-Type']
                    del headers['Content-Type']
                    r = self.pool_manager.request(
                        method, url,
                        fields=post_params,
                        encode_multipart=True,
                        preload_content=_preload_content,
                        timeout=timeout,
                        headers=headers)
                    headers['Content-Type'] = content_type_header
                # Pass a `string` parameter directly in the body to support
                # other content types than Json when `body` argument is
                # provided in serialized form
                elif isinstance(body, str) or headers['Content-Type'] == 'application/octet-stream':
                    request_body = body
                    preload = _preload_content
                    if headers['Content-Type'] == 'application/octet-stream':
                        preload = False

                    r = self.pool_manager.request(
                        method, url,
                        body=request_body,
                        preload_content=preload,
                        timeout=timeout,
                        headers=headers)
                else:
                    # Cannot generate the request from given parameters
                    msg = """Cannot prepare a request message for provided
                             arguments. Please check that your arguments match
                             declared content type."""
                    raise ApiException(status=0, reason=msg)
            # 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)
        except Exception as e:
            logger.error(str(e))
            raise

        # HANDLE REDIRECT MANUALLY
        if r.status == 302:
            logger.info("Received a redirect [302] request")
            # Handle redirection manually
            location = r.headers.get('Location')
            logger.info("Redirecting request from %s to %s ", url, location)
            headers = headers.copy()
            if location:
                # Handle custom header case
                if 'X-Redirect-Token' in r.headers:
                    logger.debug("X-Redirect-Token found")
                    custom_header_value = r.headers['X-Redirect-Token']
                    headers['Cookie'] = custom_header_value
                else:
                    if 'Authorization' in headers:
                        del headers['Authorization']
                    if 'Cookie' in headers:
                        del headers['Cookie']

                # Make a new request to the URL specified in the Location header
                redirect_response = self.pool_manager.request(method, location,
                                                              fields=query_params,
                                                              preload_content=_preload_content,
                                                              timeout=timeout,
                                                              headers=headers)
                r = redirect_response
            else:
                logger.error("Redirect location not found in 302 response headers.")

        r = RESTResponse(r)

        # Print log statements
        logger.info("Response Status: %s %s", r.status, r.reason)
        # Print debug logs, if enabled
        if self.__configuration.debug:
            logger.debug("Response Headers:")
            for key, value in six.iteritems(r.getheaders()):
                logger.debug("%s: %s", key, value)

            if r.getheader("Content-Type", "application/json") not in ['application/octet-stream', 'application/pdf', 'application/zip']:
                logger.debug("Response Body: %s", r.urllib3_response.data)

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

        return r

    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, _preload_content=True, _request_timeout=None):
        return self.request("OPTIONS", url,
                            headers=headers,
                            query_params=query_params,
                            post_params=post_params,
                            _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, _preload_content=True, _request_timeout=None):
        return self.request("POST", url,
                            headers=headers,
                            query_params=query_params,
                            post_params=post_params,
                            _preload_content=_preload_content,
                            _request_timeout=_request_timeout,
                            body=body)

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

    def PATCH(self, url, headers=None, query_params=None, post_params=None,
              body=None, _preload_content=True, _request_timeout=None):
        return self.request("PATCH", url,
                            headers=headers,
                            query_params=query_params,
                            post_params=post_params,
                            _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
            self.body = (http_resp.urllib3_response.data.decode('utf8') if hasattr(http_resp, 'urllib3_response')
                        else http_resp.data.decode('utf8'))
            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)

        logger.error(error_message)
        return error_message