import os
import logging
import zmq

import helper

from messagehandlerbuilder import SchedCompMessageHandlerBuilder
from schedcomp import CronTabInteractor, CronTabService, EventDefinition
from timeutil import RealClock, RealSleeper
from zeromqmessagehandler import ZeroMqMessageBus, ZeroMqMessageHandler

COMP_NAME = "SchedComp"
logger = logging.getLogger(COMP_NAME)


def main():
    config_path = './config.json'
    if "CONFIG_PATH" in os.environ:
        config_path = os.environ["CONFIG_PATH"]

    config = helper.read_json_from_file_as_dictionary(config_path)

    log_path = config_path
    if "LOG_PATH" in os.environ:
        log_path = os.environ["LOG_PATH"]
    helper.config_logger(log_path, COMP_NAME, add_error_handler=True)

    context = zmq.Context()
    message_bus = ZeroMqMessageBus(COMP_NAME, context, logger)
    clock = RealClock()
    sleeper = RealSleeper()
    interactors = []
    for entry in config["cronTab"]:
        event_definition = EventDefinition(entry["subject"], entry.get("type"), entry.get("data"), entry.get("headers"))
        interactors.append(CronTabInteractor(message_bus, entry["expression"], event_definition, clock, sleeper))

    cron_tab_service = CronTabService(interactors)
    cron_tab_service.start()

    message_handler = ZeroMqMessageHandler(context,
                                           COMP_NAME,
                                           message_bus,
                                           SchedCompMessageHandlerBuilder(),
                                           logger)
    message_handler.handle_messages()


if __name__ == '__main__':
    main()
