import os
import sys

import cfgtools

import logging

from cfgtools import Group
from helper import import_pydevd, config_logger
from messagehandlerbuilder import ElectronicPaymentMessageHandlerBuilder
from msgbus import MBEasyContext
from mbcontextmessagehandler import MbContextMessageBus, MbContextMessageHandler

COMPONENT_NAME = "ElectronicPayment"
DEBUG_PORT = 9132
REQUIRED_SERVICES = "StoreWideConfig"


def main():
    loader_path = os.environ["LOADERCFG"]

    import_pydevd(loader_path, DEBUG_PORT, False)
    config_logger(loader_path, COMPONENT_NAME, max_files=100, max_size=12582912, add_error_handler=True)

    logger = logging.getLogger(COMPONENT_NAME)

    config = cfgtools.read(loader_path).find_group("ElectronicPayment")  # type: Group

    try:
        message_bus = MbContextMessageBus(MBEasyContext(COMPONENT_NAME))

        message_handler_builder = ElectronicPaymentMessageHandlerBuilder(message_bus, config, logger)

        message_handler = MbContextMessageHandler(
            message_bus,
            config.find_value("ServiceName"),
            "Payment",
            REQUIRED_SERVICES,
            message_handler_builder)
        return message_handler.handle_events()
    except:
        logger.exception('exception on start')
        raise
