from typing import Any
from ._DefaultMessageProcessor import DefaultMessageProcessor
from messagebus import (
    DefaultToken,
    DataType,
    Event,
    Message,
    MessageBus,
)


class BaseUpdaterProcessor(DefaultMessageProcessor):
    def __init__(
        self,           # type: BaseUpdaterProcessor
    ):
        # type: (...) -> None

        super(BaseUpdaterProcessor, self).__init__()

    def call_business(
        self,   # type: BaseUpdaterProcessor
        _,      # type: Any
    ):
        # type: (...) -> Any

        raise NotImplementedError()

    def format_response(
        self,           # type: BaseUpdaterProcessor
        message_bus,    # type: MessageBus
        message,        # type: Message
        event,          # type: Event
        _,              # type: Any
        response,       # type: Any
    ):
        # type: (...) -> None

        reply_message = Message(
            token=DefaultToken.TK_SYS_ACK,
            data_type=DataType.param,
            data=response,
        )
        if message:
            message_bus.reply_message(
                message=message,
                reply_message=reply_message,
            )
        elif event:
            message_bus.reply_event(
                event=event,
                reply_message=reply_message,
            )

    def format_exception(
        self,           # type: BaseUpdaterProcessor
        message_bus,    # type: MessageBus
        message,        # type: Message
        event,          # type: Event
        input_obj,      # type: Any
        exception,      # type: Any
    ):
        # type: (...) -> None

        self._reply_exception(
            event=event,
            exception=exception,
            message=message,
            message_bus=message_bus
        )

    @staticmethod
    def _reply_exception(
        event,          # type: Event
        exception,      # type: Any
        message,        # type: Message
        message_bus,    # type: MessageBus
    ):
        # type: (...) -> None

        reply_message = Message(
            token=DefaultToken.TK_SYS_NAK,
            data_type=DataType.param,
            data=str(exception)
        )
        if message:
            reply_message = Message(
                token=DefaultToken.TK_SYS_NAK,
                data_type=DataType.param,
                data=str(type(exception).__name__)
            )
            message_bus.reply_message(
                message=message,
                reply_message=reply_message
            )
        elif event:
            message_bus.reply_event(
                event=event,
                reply_message=reply_message
            )
