import sys
import base64

if sys.version_info[0] < 3:
    import httplib as http_client
else:
    import http.client as http_client


class HTTPClient:

    def __init__(self, cfg):
        self.config = cfg
        if self.config.port == 443:
            self.httpConnector = http_client.HTTPSConnection
        else:
            self.httpConnector = http_client.HTTPConnection
        self.authorization_token = base64.b64encode(
            str.encode("{}:{}".format(self.config.auth_user, self.config.auth_password)))

    def get_header(self, path):
        '''
            header = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": "Basic VlQ1MkpOODg6MUZUTVclbjc2" + self.authorization_token
        }
        '''
        header = {
            "Authorization": "Basic " + self.authorization_token.decode("utf-8")
        }
        return header

    def _post(self, path, body):
        header = self.get_header(path)
        con = self.httpConnector(self.config.host, self.config.port)
        con.request("POST", path, body, header)
        res = con.getresponse()
        return res.read()

    def gateway_check(self, body):
        path = self.config.gateway_check_url
        return self._post(path, body)

    def gateway_error(self, body):
        path = self.config.gateway_error_url
        return self._post(path, body)
