import zmq

from typing import Optional
from zeromqthreadpool import ZeroMqThreadPool, ThreadPoolParameters

from messagehandler import MessageHandlerBuilder
from ._HandleEventWorkerThread import HandleEventWorkerThread
from ._HandleRequestWorkerThread import HandleRequestWorkerThread


class ZeroMqMessageHandler(object):
    def __init__(self, context, pub_address, pull_address, rep_address, message_handler_builder, logger=None):
        # type: (zmq.Context, str, Optional[str], Optional[str], MessageHandlerBuilder) -> None
        self.context = context
        self.message_handler_builder = message_handler_builder
        self.message_handler_builder.build_singletons()

        self.handle_event_thread_pool = None
        if pull_address is not None:
            self.handle_event_thread_pool = ZeroMqThreadPool(
                self.context,
                ThreadPoolParameters(5, 50, 5, 2000, 2000),
                pull_address,
                False,
                HandleEventWorkerThread,
                self.message_handler_builder,
                pub_address,
                logger)

        self.handle_request_thread_pool = None
        if rep_address is not None:
            self.handle_request_thread_pool = ZeroMqThreadPool(
                self.context,
                ThreadPoolParameters(5, 50, 5, 2000, 2000),
                rep_address,
                False,
                HandleRequestWorkerThread,
                self.message_handler_builder,
                pub_address,
                logger)

    def handle_messages(self):
        if self.handle_event_thread_pool is not None:
            self.handle_event_thread_pool.join()
        if self.handle_request_thread_pool is not None:
            self.handle_request_thread_pool.join()

        self.message_handler_builder.destroy_singletons()
