import os

import pyscripts
from cfgtools import read
from helper import import_pydevd, config_logger
from logging import getLogger
from msgbus import MBEasyContext
from mbcontextmessagehandler import MbContextMessageBus, MbContextMessageHandler

from externals.messagehandlerbuilder import ComponentMessageHandlerBuilder
from externals.messages import ListenedEvents


LOADER_CFG = os.environ["LOADERCFG"]


def main():
    import_pydevd(LOADER_CFG, 9127, False)

    config = read(LOADER_CFG)

    goals_filename = config.find_value("DailyGoals.goalsCacheFileName")

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

    mb_context = MBEasyContext(service_name)
    pyscripts.mbcontext = mb_context

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

    message_bus = MbContextMessageBus(mb_context)
    message_handler_builder = ComponentMessageHandlerBuilder(mb_context, persistence_name, goals_filename)

    message_handler = MbContextMessageHandler(
        message_bus,
        service_name,
        service_name,
        required_services,
        message_handler_builder
    )

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

    message_handler.subscribe_reentrant_events([ListenedEvents.ORDER_MODIFIED.value, ListenedEvents.TABLE_CLOSED.value])
    message_handler.handle_events()


if __name__ == "__main__":
    main()
