import os

import sysactions
from configurator import Configurator
from mbcontextmessagehandler import MbContextMessageBus, MbContextMessageHandler
from messagehandlerbuilder import ServiceMessageHandlerBuilder
from msgbus import MBEasyContext


def main():
    # type: () -> None

    loader_path = os.environ["LOADERCFG"]

    configurator = Configurator(loader_path)
    configs = configurator.read_loader_configs()
    logger = configurator.configure_logger()

    mb_context = MBEasyContext(configs.component_name)
    message_bus = MbContextMessageBus(mb_context)
    sysactions.mbcontext = mb_context

    service_message_handler_builder = ServiceMessageHandlerBuilder(logger, configs, message_bus)
    message_handler = MbContextMessageHandler(message_bus,
                                              configs.component_name,
                                              configs.component_name,
                                              configs.required_services,
                                              service_message_handler_builder)

    logger.debug("Starting messagebus [{}] ...".format(configs.component_name))
    return message_handler.handle_events()


if __name__ == "__main__":
    main()
