import signal
import sys
from multiprocessing import Queue, cpu_count

import analysis
import database
import settings
from filemanager import FileManager


class Cleaner:

    def __init__(self, file_manager, control_queue):
        self.fm = file_manager
        self.logger = settings.get_logger('MAIN')
        self.worker = []
        self.control = control_queue

    def cleanup(self, signum, frame):
        self.logger.info('Received interrupt, signalling the FileManager to stop')
        self.fm.terminate()
        self.fm.join()
        self.logger.info('FileManager finished')
        for w in self.worker:
            self.logger.log(settings.VERBOSE, f'Shutting down {repr(w)}')
            w.terminate()
        for w in self.worker:
            w.join()
        self.logger.info('Finished cleanup, exiting now')
        sys.exit(0)

    def run(self):
        signal.signal(signal.SIGTERM, self.cleanup)
        signal.signal(signal.SIGINT, self.cleanup)
        for i in range(cpu_count()):
            w = analysis.Worker(str(i), inputs, results)
            w.start()
            self.worker.append(w)
        message = None
        while message != 'shutdown':
            message = str(self.control.get())
        self.logger.info('Received shutdown message')
        self.cleanup(None, None)


if __name__ == '__main__':
    inputs = Queue()
    results = Queue()
    control = Queue()
    vt, queries, csv, vt_quota, run = settings.init()
    fm = FileManager(inputs, results, control, run, vt, queries, vt_quota_used=vt_quota)
    rows = database.create()
    if rows == 0:
        database.populate(csv)
    cl = Cleaner(fm, control)
    fm.start()
    cl.run()
