import os

from logging import getLogger

from cfgtools import read
from msgbus import MBEasyContext
from helper import import_pydevd
from mwhelper import config_logger_parse_file_name
from mbcontextmessagehandler import MbContextMessageBus, MbContextMessageHandler

from externals.messagehandlerbuilder import ComponentMessageHandlerBuilder

LOADER_CFG = os.environ["LOADERCFG"]


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

    import_pydevd(LOADER_CFG, 9179)

    reader = read(LOADER_CFG)
    service_name = str(reader.find_value("Identification.ComponentName"))
    required_services = "|".join(reader.find_values(service_name + "." + "RequiredServices"))
    persistence_name = reader.find_value(service_name + "." + "RequiredServices").encode("utf-8")

    config_logger_parse_file_name(os.environ["LOG_PATH"], service_name)
    logger = getLogger(__name__)

    mb_context = MBEasyContext(service_name)
    message_bus = MbContextMessageBus(mb_context)
    message_handler_builder = ComponentMessageHandlerBuilder(mb_context, persistence_name)
    message_handler = MbContextMessageHandler(
        message_bus,
        service_name,
        service_name,
        required_services,
        message_handler_builder
    )

    logger.warning("Starting {} Component".format(service_name))
    message_handler.handle_events()


if __name__ == "__main__":
    main()
