from logging import getLogger

from messagebus import Message, DefaultToken, DataType
from messageprocessorutil import UuidMessageProcessor

from nperipherals_core.interactor.print_interactor import PrintInteractor

logger = getLogger(__name__)


class PrintProcessor(UuidMessageProcessor):
    def __init__(self, interactor, event_name=None):
        # type: (PrintInteractor, str) -> None

        super(PrintProcessor, self).__init__(event_name)

        self.interactor = interactor

    def parse_data(self, data, event_type):
        return data

    def call_business(self, obj):
        self.interactor.print_data(obj)

    def format_response(self, message_bus, message, event, input_obj, result):
        message_bus.reply_message(message, Message(DefaultToken.TK_SYS_ACK, DataType.string, "ok"))
        logger.info("PrintProcessor ACK")

    def format_exception(self, message_bus, message, event, input_obj, exception):
        self._reply_nak(exception, message, message_bus)

    def format_parse_exception(self, message_bus, message, event, data, exception):
        self._reply_nak(exception, message, message_bus)

    @staticmethod
    def _reply_nak(exception, message, message_bus):
        message_bus.reply_message(message, Message(DefaultToken.TK_SYS_NAK, DataType.param, repr(exception)))
        logger.error(repr(exception))
