import logging
import logging.config
import os

import zmq
from diagnostics import DiagnosticMonitor
from helper import config_logger, read_json_from_file_as_dictionary
from messagehandlerbuilder import EventManagerMessageHandlerBuilder, ConfigKey
from zeromqmessagehandler import ZeroMqMessageBus, ZeroMqMessageHandler

COMP_NAME = "EventManager"

logger = logging.getLogger(COMP_NAME)


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

    if os.path.isfile(config_path):
        config = read_json_from_file_as_dictionary(config_path)
    else:
        config = {}

    if "PUBLIC_HOSTNAME" in os.environ:
        config[ConfigKey.PUBLIC_HOSTNAME] = os.environ["PUBLIC_HOSTNAME"]

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

    monitor = None
    if os.environ.get("DIAGNOSTIC_MONITOR", "").lower() in ("1", "true", "yes"):
        try:
            interval = int(os.environ.get("DIAGNOSTIC_INTERVAL", "1800"))
        except ValueError:
            interval = 1800
        monitor = DiagnosticMonitor(
            interval_seconds=interval,
            enable_tracemalloc=os.environ.get("DIAGNOSTIC_TRACEMALLOC", "").lower() in ("1", "true"),
        )
        monitor.start()

    context = zmq.Context()

    message_bus = ZeroMqMessageBus(COMP_NAME, context)

    message_handler_builder = EventManagerMessageHandlerBuilder(context, config, message_bus, logger)
    message_handler = ZeroMqMessageHandler(context,
                                           COMP_NAME,
                                           message_bus,
                                           message_handler_builder)
    try:
        message_handler.handle_messages()
    finally:
        if monitor is not None:
            monitor.stop()
        message_handler_builder.destroy_singletons()
    message_bus.dispose()


if __name__ == '__main__':
    main()
