import logging
from threading import Thread

from typing import List
from ._CronTabInteractor import CronTabInteractor


logger = logging.getLogger("SchedComp")


class CronTabService(object):
    def __init__(self, interactors):
        # type: (List[CronTabInteractor]) -> None
        self.interactors = interactors
        self.threads = []
        self.running = False

        for i in range(0, len(self.interactors)):
            t = Thread(target=self.run, args=(i, ))
            t.daemon = True
            self.threads.append(t)

    def start(self):
        self.running = True
        for thread in self.threads:
            thread.start()

    def stop(self):
        self.running = False

    def run(self, index):
        while self.running:
            try:
                self.interactors[index].execute()
            except:
                logger.exception("Error handling cron job: {}".format(self.interactors[index].event_definition))
