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

from .._ServiceLocator import ServiceLocator


class RegisterServiceProcessor(UuidMessageProcessor):

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

    def parse_data(self, data, event_type):
        parts = data.split(b"\0")
        if len(parts) < 2:
            raise Exception("Invalid register message")
        service_name = parts[0].decode("utf-8")
        service_address = parts[1].decode("utf-8")
        return RegisterServiceRequest(service_name, service_address)

    def call_business(self, request):
        # type: (RegisterServiceRequest) -> None
        return self.service_locator.register_service(request.service_name, request.address)

    def format_response(self, message_bus, message, event, input_obj, reg_id):
        message_bus.reply_message(message, AckMessage(reg_id.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")))
