import logging
import os

import zmq
from helper import config_logger, read_json_from_file_as_dictionary
from zeromqmessagehandler import ZeroMqMessageBus, ZeroMqMessageHandler

from messagehandlerbuilder import ServiceLocatorMessageHandlerBuilder

COMP_NAME = "ServiceLocator"

logger = logging.getLogger(COMP_NAME)


def main():
    config_path = './config.json'
    if "CONFIG_PATH" in os.environ:
        config_path = os.environ["CONFIG_PATH"]

    if os.path.isfile(config_path):
        config = read_json_from_file_as_dictionary(config_path)
    else:
        config = {}

    if "locatorAddress" in config:
        locator_address = config["locatorAddress"]
    else:
        locator_address = "tcp://*:6000"

    log_path = config_path
    if "LOG_PATH" in os.environ:
        log_path = os.environ["LOG_PATH"]
    config_logger(log_path, COMP_NAME, add_error_handler=True)

    context = zmq.Context()

    message_bus = ZeroMqMessageBus(COMP_NAME, context)

    message_handler_builder = ServiceLocatorMessageHandlerBuilder(config, logger)
    message_handler = ZeroMqMessageHandler(context,
                                           COMP_NAME,
                                           message_bus,
                                           message_handler_builder,
                                           service_address=locator_address,
                                           publish_service=False)
    message_handler.handle_messages()


if __name__ == '__main__':
    main()
