import json
import logging
import os

from hyper_visor.message_handler_builder import HyperVisorMessageHandlerBuilder
from helper import config_logger
from mbcontextmessagehandler import (
    MbContextMessageBus,
    MbContextMessageHandler,
)
from msgbus import (
    MBEasyContext,
)


def default_log_config():
    return {
        "version": 1,
        "formatters": {
            "defaultFormatter": {
                "()": "helper.IsoFormatter"
            }
        },
        "handlers": {
            "stdout": {
                "class": "logging.StreamHandler",
                "formatter": "defaultFormatter",
                "level": "DEBUG",
                "stream": "ext://sys.stdout",
            },
            "stderr": {
                "class": "logging.StreamHandler",
                "formatter": "defaultFormatter",
                "level": "ERROR",
                "stream": "ext://sys.stderr",
            },
        },
        "root": {
            "level": "DEBUG",
            "handlers": [
                "stdout",
                "stderr"
            ]
        },
        "disable_existing_loggers": False
    }


logger = logging.getLogger(__name__)


def main():

    if "HVIP" not in os.environ:
        os.environ["HVIP"] = "0.0.0.0"
    if "HVPORT" not in os.environ:
        os.environ["HVPORT"] = "16000"
    if "HVCOMPPORT" not in os.environ:
        os.environ["HVCOMPPORT"] = os.environ["HVPORT"]

    log_path = os.environ.get("LOG_PATH", "{}")
    try:
        log_dict = json.loads(log_path)
        if len(log_dict) == 0:
            log_dict = default_log_config()

        config_logger(log_dict)
    except ValueError:
        config_logger(log_path)

    mb_context = MBEasyContext(name="ServiceLocator")
    message_bus = MbContextMessageBus(mb_context=mb_context)

    message_handler_builder = HyperVisorMessageHandlerBuilder(mb_context=mb_context)
    message_handler = MbContextMessageHandler(
        message_bus=message_bus,
        service_name="",
        service_type="",
        required_services=[],
        message_handler_builder=message_handler_builder,
    )
    logger.info("Starting ServiceLocator")
    return message_handler.handle_messages()


if __name__ == "__main__":
    main()
