from typing import (
    List,
    Optional,
)

from messagebus import (
    Event,
    Message,
    MessageBus,
)
from messagehandler import (
    MessageHandler,
    MessageHandlerBuilder,
)
from ._EventHttpMessageHandler import EventHttpMessageHandler


class EventHttpMessageHandlerBuilder(MessageHandlerBuilder):

    def __init__(
        self,
        message_bus: MessageBus,
        message_handler_builder: MessageHandlerBuilder,
        http_events: List[str],
        fields_to_pass_through: Optional[List[str]] = None
    ) -> None:

        self.message_bus = message_bus
        self.message_handler_builder = message_handler_builder
        self.http_events = http_events
        self.fields_to_pass_through = fields_to_pass_through

        self.event_http_message_handler: Optional[EventHttpMessageHandler] = None

    def build_singletons(
        self,
    ) -> None:

        self.message_handler_builder.build_singletons()

        self.event_http_message_handler = EventHttpMessageHandler(
            message_bus=self.message_bus,
            message_handler_builder=self.message_handler_builder,
            fields_to_pass_through=self.fields_to_pass_through,
        )

    def build_message_handler(
        self,
        message: Message,
        event: Event,
    ) -> MessageHandler:

        if event is not None and event.subject in self.http_events:
            return self.event_http_message_handler

        return self.message_handler_builder.build_message_handler(
            message=message,
            event=event,
        )

    def destroy_message_handler(
        self,
        message_handler: MessageHandler,
    ) -> None:

        if message_handler != self.event_http_message_handler:
            self.message_handler_builder.destroy_message_handler(message_handler=message_handler)

    def destroy_singletons(
        self,
    ) -> None:

        self.message_handler_builder.destroy_singletons()
