import os
import sys

import sysactions
from configurator import Configurator
from flaskmessagehandler import FlaskMessageHandler
from helper import import_pydevd
from httpmessagehandler import HttpMessageHandler
from mbcontextmessagehandler import MbContextMessageBus
from messagehandlerbuilder import ServiceMessageHandlerBuilder
from model.config import Config
from msgbus import MBEasyContext, MBException
from syserrors import SE_MB_ERR, SE_SUCCESS


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

    loader_path = os.environ["LOADERCFG"]

    import_pydevd(loader_path, 9178)

    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

    _wait_for_message_bus_required_services(message_bus, configs)

    service_message_handler_builder = ServiceMessageHandlerBuilder(logger, configs, message_bus, flask_server=True)
    http_message_handler = HttpMessageHandler(service_message_handler_builder, configs.cors_origin_hosts)
    flask_message_handler = FlaskMessageHandler(http_message_handler)

    logger.debug("Starting flask [{}] ...".format(configs.component_name))
    return flask_message_handler.run(configs.component_name, configs.host, configs.port)


def _wait_for_message_bus_required_services(message_bus, configs):
    # type: (MbContextMessageBus, Config) -> None

    try:
        exported_services = "{}:{}".format(configs.component_name, configs.component_name)
        status = message_bus.mbcontext.MB_EasyWaitStart(exported_services, configs.required_services)
        if status != SE_SUCCESS:
            sys.exit(status)
    except MBException:
        sys.exit(SE_MB_ERR)


if __name__ == "__main__":
    main()
