import os
import sys
import subprocess
from threading import Thread

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

from apps.log import *

from apps.messages import *
from apps.populate_cve import PopulateCVE
from apps.update_cve import UpdateCVE

def load_settings():
    st = settings.Settings()
    return st.load()


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


class PopulaterCVE():

    def __init__(self, settings):
        self.settings = settings

    def run(self):
        logme('run populate of CVE database...', CODE_NORMAL)
        populate_cve = PopulateCVE(self.settings)
        populate_cve.run()

class UpdaterCVE():

    def __init__(self, settings):
        self.settings = settings

    def run(self):
        logme('run update of CVE database...', CODE_NORMAL)
        update_cve = UpdateCVE(self.settings)
        update_cve.run()

def test():
    settings = load_settings()

    from apps.cache import Cache
    cache = Cache()
    cache.db.flushall()

    from apps.mongo import Mongo
    mongo = Mongo()
    mongo.drop_db()

    if mongo.elements_count() == 0:
        populate = PopulaterCVE(settings)
        populate.run()

    update = UpdaterCVE(settings)
    update.run()

    logme('run task polling...', CODE_NORMAL)
    uri = "python " + os.path.join(runPath, "task_polling.py")
    logme('run: %s' % uri, CODE_NORMAL)
    poller = subprocess.Popen(
        uri,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE)
    poller.wait()
    poller.communicate()
    print (poller)

def runPPD():
    populate = PopulaterCVE(settings)
    populate.run()

def tunUPD():
    update = UpdaterCVE(settings)
    update.run()

def test2():
    settings = load_settings()

    from apps.cache import Cache
    cache = Cache()
    cache.db.flushall()

    from apps.mongo import Mongo
    mongo = Mongo()
    mongo.drop_db()

    ppdname = "Populate thread"
    tppd = Thread()


    # uri = "python " + os.path.join(runPath, "populate_cve.py")
    # logme('run: %s' % uri, CODE_NORMAL)
    # pop = subprocess.Popen(
    #     uri,
    #     stderr=subprocess.PIPE,
    #     stdout=subprocess.PIPE
    # )
    # pop.wait()
    # pop.communicate()
    # print(pop)
    #
    # uri = "python " + os.path.join(runPath, "update_cve.py")
    # logme('run: %s' % uri, CODE_NORMAL)
    # upd = subprocess.Popen(
    #     uri,
    #     stderr=subprocess.PIPE,
    #     stdout=subprocess.PIPE
    # )
    # upd.wait()
    # upd.communicate()
    # print(upd)
    #
    # logme('run: %s' % uri, CODE_NORMAL)
    # poller = subprocess.Popen(
    #     uri,
    #     stderr=subprocess.PIPE,
    #     stdout=subprocess.PIPE)
    # poller.wait()
    # poller.communicate()
    # print (poller)

def main():
    settings = load_settings()

    test2()

    logme('job complete', CODE_COMPLETE)

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