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

from .._ServiceLocator import ServiceLocator


class LocateServiceProcessor(UuidMessageProcessor):

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

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

    def call_business(self, service_name):
        # type: (str) -> None
        return self.service_locator.locate_service(service_name)

    def format_response(self, message_bus, message, event, service_name, service_address):
        if service_address is not None:
            message_bus.reply_message(message, AckMessage(data=service_address.encode("utf-8")))
        else:
            message_bus.reply_message(message, NakMessage("Service {} not found".format(service_name).encode("utf-8")))

    def format_exception(self, message_bus, message, event, input_obj, exception):
        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")))
