from mbcontextmessagehandler import MbContextMessageBus
from messagebus import (
    DefaultToken,
    DataType,
    Message,
    Event,
)

from application.interactor import LoyaltyIdentifierInteractor
from application.model import AsyncUuidMessageProcessor


class LoyaltyIdentifierProcessor(AsyncUuidMessageProcessor):
    def __init__(
        self,
        interactor,     # type: LoyaltyIdentifierInteractor
    ):
        # type: (...) -> None

        super(LoyaltyIdentifierProcessor, self).__init__()
        self.interactor = interactor

    def parse_data(
        self,
        data,           # type: str
        event_type,     # type: str
    ):
        # type: (...) -> str

        return str(data)

    def call_business(
        self,
        key,    # type: str
    ):
        # type: (...) -> str

        return self.interactor.get_key(key=key)

    def format_response(
        self,
        message_bus,    # type: MbContextMessageBus
        message,        # type: Message
        event,          # type: Event
        request,        # type: None
        response,       # type: str
    ):
        # type: (...) -> None

        if response:
            message_bus.reply_message(
                message=message,
                reply_message=Message(
                    token=DefaultToken.TK_SYS_ACK,
                    data_type=DataType.string,
                    data=response,
                ),
            )
        else:
            message_bus.reply_message(
                message=message,
                reply_message=Message(token=DefaultToken.TK_SYS_NAK),
            )

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

        message_bus.reply_message(
            message=message,
            reply_message=Message(
                token=DefaultToken.TK_SYS_NAK,
                data_type=DataType.param,
                data=str(exception),
            ),
        )

    def format_parse_exception(
        self,
        message_bus,    # type: MbContextMessageBus
        message,        # type: Message
        event,          # type: Event
        data,           # type: None
        exception,      # type: Exception
    ):
        # type: (...) -> None

        message_bus.reply_message(
            message=message,
            reply_message=Message(
                token=DefaultToken.TK_SYS_NAK,
                data_type=DataType.param,
                data=str(exception),
            ),
        )
