import os
import sys
runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))

import datetime
from xml.sax import make_parser

from apps.messages import *

from apps.tasks import *
from apps.getfile import getFile
from apps.handlers.cvehandler import CVEHandler

def logme(message, code=0):
    makelog(os.path.basename(__file__), message, code)


class PopulateCVE():

    def __init__(self, settings):
        self.settings = settings
        self.mongo = Mongo()
        self.cache = Cache()
        self.file_prefix = self.settings['cve_file_prefix']
        self.file_suffix = self.settings['cve_file_suffix']
        self.file_mod = self.settings['cve_file_mod']
        self.file_rec = self.settings['cve_file_rec']
        self.date = datetime.datetime.now()
        self.year = self.date.year + 1
        self.cveStartYear = self.settings['start_year']
        self.verbose = self.settings['verbose']


    def run(self):
        logme('database population started')
        for x in range(self.cveStartYear, self.year):
            logme('try to parse %s year' % x)
            parser = make_parser()
            ch = CVEHandler()
            parser.setContentHandler(ch)
            getfile = self.file_prefix + str(x) + self.file_suffix
            url = self.settings['source_cve'] + getfile
            try:
                (f, r) = getFile(url)
                logme('file %s downloaded' % url, CODE_NORMAL)
            except:
                logme('cannot open URL %s' % url, CODE_FILE_ERROR)
                return False
            parser.parse(f)
            logme('file %s parsed' % getfile, CODE_NORMAL)
            if self.verbose:
                for item in ch.cves:
                    print('processing %s ' % item['id'])
            for item in ch.cves:
                if 'cvss' in item:
                    item['cvss'] = float(item['cvss'])
            if len(ch.cves) != 0:
                logme("Importing CVEs for year " + str(x))
                make_task_insertCVE(ch.cves)
            else:
                logme("Year " + str(x) + " has no CVE's.", 1)
        logme('complete populate database', CODE_NORMAL)

def main():
    from settings import settings
    st = settings.Settings()
    populate = PopulateCVE(st.load())
    from apps.mongo import Mongo
    mongo = Mongo()
    if mongo.elements_count() == 0:
        mongo.close()
        populate.run()
    return 0

if __name__ == '__main__':
    # sys.exit(main())
    print('complete')