import logging
import os
import signal
from concurrent.futures.thread import ThreadPoolExecutor

import zmq
from helper import (
    config_logger,
    read_json_from_file_as_dictionary,
)
from messagehandlerbuilder import (
    Configuration,
    RedisConfig,
    ServiceLocatorMessageHandlerBuilder,
    StoreStrategy,
)
from messagereceiver import (
    MultiStrategyMessageReceiver,
    ThreadPoolExecutorHandleMessageStrategy,
)
from zeromqlowlevelmessagebus import ZeroMqLowLevelMessageBus

COMP_NAME = "ServiceLocator"

logger = logging.getLogger(__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_dict = read_json_from_file_as_dictionary(config_path)
    else:
        config_dict = {}

    port = config_dict.get("port", 6000)
    store_strategy = StoreStrategy.IN_MEMORY
    redis_config = None
    if "redis" in config_dict:
        store_strategy = StoreStrategy.REDIS
        redis_dict = config_dict["redis"]
        redis_config = RedisConfig(
            host=redis_dict["host"],
            port=redis_dict["port"],
            db=redis_dict["db"],
            ssl=redis_dict["ssl"],
        )
    registration_expiration = 20
    if "registrationExpiration" in config_dict:
        registration_expiration = config_dict["registrationExpiration"]

    log_path = config_path
    if "LOG_PATH" in os.environ:
        log_path = os.environ["LOG_PATH"]

    config_logger(loader_path=log_path)

    context = zmq.Context()

    message_bus = ZeroMqLowLevelMessageBus(
        context=context,
        port=port,
    )

    message_handler_builder = ServiceLocatorMessageHandlerBuilder(
        config=Configuration(
            store_strategy=store_strategy,
            registration_expiration=registration_expiration,
            redis_config=redis_config,
        ),
    )

    message_receiver = MultiStrategyMessageReceiver(
        message_bus=message_bus,
        message_handler_builder=message_handler_builder,
        poll_timeout=1000,
        handle_strategy=ThreadPoolExecutorHandleMessageStrategy(thread_pool_executor=ThreadPoolExecutor(max_workers=50))
    )

    def signal_handler(signum, frame):
        print(f"Received {signum}")
        logger.info(f"Received {signum}")
        message_receiver.stop()

    signal.signal(signal.SIGINT, signal_handler)

    message_receiver.receive_messages()
    logger.info("Terminei")
    print("Terminou")


if __name__ == '__main__':
    main()
