import http.client, json, urllib

from base64 import b64encode

from ivulncheck_client.lib.config_client import Configuration as conf

IVULNCHECK_API_FQDN = conf.getIvulncheckAPIHost()
IVULNCHECK_API_PORT = conf.getIvulncheckAPIPort()
IVULNCHECK_API_USERNAME = conf.getIvulncheckAPIUsername()
IVULNCHECK_API_PASSWORD = conf.getIvulncheckAPIPassword()

class APIError(Exception):
    def __init__(self, message, status=500):
        self.message = message
        self.status  = status

def request_api(method, url_suffix, filters=None):
    data = None
    # First try HTTPS
    try:
        conn = http.client.HTTPSConnection(IVULNCHECK_API_FQDN, IVULNCHECK_API_PORT)
        conn.connect()
    except Exception as e:
        conn = http.client.HTTPConnection(IVULNCHECK_API_FQDN, IVULNCHECK_API_PORT)
        
    try:
        userpass = b64encode((IVULNCHECK_API_USERNAME + ":" + IVULNCHECK_API_PASSWORD).encode("ascii")).decode("ascii")
        
        if filters:
            body=urllib.parse.urlencode(filters)
            headers = {"Authorization" : "Basic " + userpass, "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
            conn.request(method, url_suffix, body, headers)
        else:
            headers = {"Authorization" : "Basic " + userpass}
            conn.request(method, url_suffix, headers=headers)
        
        data = json.loads(conn.getresponse().read().decode("utf-8"))
    except Exception as e:
        raise(APIError("Ivulncheck API unreachable : " + str(e)))
    finally:
        conn.close()
        if type(data) is dict  and 'error' in data.keys():
            raise(APIError("APIError : " + data['message']))
    return data
