import http.client, json, datetime, urllib

from ivulncheck_web.lib.config_web import Configuration as conf

import logging
logging.basicConfig(filename=conf.getLogfile(), level=logging.INFO)

CVESEARCH_API_FQDN = conf.getCVESearchAPIHost()
CVESEARCH_API_PORT = conf.getCVESearchAPIPort()

def getCVEFor(cpeid):
    rsp_str = None
    try:
        conn = http.client.HTTPConnection(CVESEARCH_API_FQDN, CVESEARCH_API_PORT)
        conn.request('GET', "/api/cvefor/" + cpeid)
        rsp = conn.getresponse()
        rsp_str = str(rsp.read().decode("utf-8"))
        if rsp_str == "[]":
            return True, []
        # To avoid " in title field making json.loads crash
        rsp_str = rsp_str.replace(r'\\"', "")
        rsp_str = rsp_str.replace(r'\'', "")
        rsp_str = rsp_str.replace(r'\\n', " ")
        rsp_str = rsp_str.replace(r'\n', " ")
        
        data = json.loads(rsp_str)
        return True, data
    except Exception as e:
        # ~ logging.info('\n\n\n\n\n\n\n\n[%s] (%s)\tResponse : %s.', datetime.datetime.today().isoformat(), __name__, rsp_str)
        logging.critical('[%s] (%s)\tCVE-Search API unreachable %s. ', datetime.datetime.today().isoformat(), __name__, type(e))
        return False, None

def getCVE(id):
    try:
        conn = http.client.HTTPConnection(CVESEARCH_API_FQDN, CVESEARCH_API_PORT)
        conn.request('GET', "/api/cve/" + id)
        rsp = conn.getresponse()
        rsp_str = str(rsp.read().decode("utf-8"))
        data =  json.loads(rsp_str)
        return True, data
    except Exception as e:
        logging.critical('[%s] (%s)\tCVE-Search API unreachable. ', datetime.datetime.today().isoformat(), __name__)
        return False, None

def getCPE(id):
    try:
        conn = http.client.HTTPConnection(CVESEARCH_API_FQDN, CVESEARCH_API_PORT)
        conn.request('GET', "/api/cpe/" + id)
        rsp = conn.getresponse()
        #~ json_rsp = re.search(r'', rsp)
        rsp_str = str(rsp.read().decode("utf-8"))
        # To avoid " in title field making json.loads crash
        rsp_str = rsp_str.replace(r'\\"', "")
        rsp_str = rsp_str.replace(r'\'', "")
        rsp_str = rsp_str.replace(r'\\n', " ")
        rsp_str = rsp_str.replace(r'\n', " ")
        data =  json.loads(rsp_str)
        return True, data
    except Exception as e:
        logging.critical('[%s] (%s)\tCVE-Search API unreachable. ', datetime.datetime.today().isoformat(), __name__)
        return False, None

def findCPE(edprodvers, filter=False):
    try:
        conn = http.client.HTTPConnection(CVESEARCH_API_FQDN, CVESEARCH_API_PORT)
        conn.request('GET', "/api/cpesearch/" + edprodvers)
        rsp = conn.getresponse()
        #~ json_rsp = re.search(r'', rsp)
        rsp_str = str(rsp.read().decode("utf-8"))
        # To avoid " in title field making json.loads crash
        rsp_str = rsp_str.replace(r'\\"', "")
        rsp_str = rsp_str.replace(r'\'', "")
        rsp_str = rsp_str.replace(r'\\n', " ")
        rsp_str = rsp_str.replace(r'\n', " ")
        data =  json.loads(rsp_str)
        return True, data
    except Exception as e:
        logging.error(e)
        logging.critical('[%s] (%s)\tCVE-Search API unreachable. ', datetime.datetime.today().isoformat(), __name__)
        return False, None
    
def findCPEid(edprodvers):
    (cvesearch_api_status, cpes) = findCPE(urllib.parse.quote_plus(edprodvers))
    if cvesearch_api_status == False:
        return False, None
    elif cpes is not None and len(cpes) > 0:
        logging.info('[%s] (%s)\t%d CPE found', datetime.datetime.today().isoformat(), __name__, len(cpes))
        for cpe in cpes:
            cpe_id = re.search(r'([\w\-\.]+\:){4}[\w\-\.]+\:?', cpe['id']).group(0)
            return True, cpe_id
    else:
        logging.info('[%s] (%s)\tNo CPE found', datetime.datetime.today().isoformat(), __name__)
        return True, None
    


    
