from messagebus import AckMessage, NakMessage
from messageprocessorutil import UuidMessageProcessor
from .dto import RegisterServiceRequest
from .. import KeepAliveError

from .._ServiceLocator import ServiceLocator


class KeepAliveProcessor(UuidMessageProcessor):

    def __init__(self, service_locator, event_name=None):
        # type: (ServiceLocator, str) -> None
        super(KeepAliveProcessor, self).__init__(event_name)
        self.service_locator = service_locator

    def parse_data(self, data, event_type):
        return data.decode("utf-8")

    def call_business(self, reg_id):
        # type: (str) -> None
        self.service_locator.keep_alive(reg_id)

    def format_response(self, message_bus, message, event, service_name, _):
        message_bus.reply_message(message, AckMessage())

    def format_exception(self, message_bus, message, event, input_obj, exception):
        if isinstance(exception, KeepAliveError):
            message_bus.reply_message(message, NakMessage(exception.message.encode("utf-8")))
        else:
            message_bus.reply_message(message, NakMessage(str(exception).encode("utf-8")))

    def format_parse_exception(self, message_bus, message, event, data, exception):
        message_bus.reply_message(message, NakMessage(str(exception).encode("utf-8")))
