from tornado.escape import utf8
from tornado.httpclient import HTTPRequest
from urllib.parse import urlparse, urlunparse

# from django.conf import settings


TORNADO_PARAMS = {'method', 'headers', 'body', 'auth_username',
                      'auth_password', 'auth_mode', 'connect_timeout',
                      'request_timeout', 'if_modified_since', 'follow_redirects',
                      'max_redirects', 'user_agent', 'use_gzip',
                      'network_interface', 'streaming_callback',
                      'header_callback', 'prepare_curl_callback', 'proxy_host',
                      'proxy_port', 'proxy_username', 'proxy_password',
                      'allow_nonstandard_methods', 'validate_cert', 'ca_certs',
                      'allow_ipv6', 'client_key', 'client_cert'}


class Request:
    def __init__(self, url, type_, name=None, headers=None, request_timeout=10,
                 method='GET', retries=None, **kwargs):

        # длинные запросы отправляем POST
        if (len(url) > 1024 * 2
                and type_ not in ('search', 'decider')  # SaaS не умеет POST для поиска
                and method == 'GET'):

            bits = list(urlparse(url))
            kwargs['body'] = utf8(bits[-2])
            bits[-2] = None

            url = urlunparse(bits)
            method = 'POST'

        self.type = type_
        self.name = name
        self.url = url
        self.headers = headers or {}
        self.request_timeout = request_timeout
        self.params = kwargs
        self.method = method
        self.retries = retries

    def get_tornado_request(self):
        request = {
            'headers': self.headers,
            'request_timeout': self.request_timeout,
            'method': self.method,
            'allow_ipv6': True,
            # 'ca_certs': settings.ISEARCH_CA_CERTS,
            'validate_cert': False,
        }

        for key, value in self.params.items():
            if key in TORNADO_PARAMS:
                request[key] = value

        return HTTPRequest(self.url, **request)
