from hyper_visor.service import (
    Service,
    ServiceLocator,
)
from messagebus import (
    AckMessage,
    InternalErrorMessage,
    NakMessage,
)
from messageprocessorutil import UuidMessageProcessor


class FindServiceProcessor(UuidMessageProcessor):
    def __init__(self, service_locator: ServiceLocator):
        super().__init__()
        self.service_locator = service_locator

    def parse_data(self, data: bytes):
        return data.decode()

    def call_business(self, service_name):
        return self.service_locator.locate(service_name=service_name)

    def format_response(
        self,
        message_bus,
        message,
        event,
        service_name: str,
        service: Service,
    ):
        if service is None:
            reply = NakMessage()
        else:
            data = f"{service.address}\0{service.port}".encode()
            reply = AckMessage(data=data)

        message_bus.reply_message(
            message=message,
            reply_message=reply,
        )

    def format_exception(self, message_bus, message, event, input_obj, exception):
        message_bus.reply_message(
            message=message,
            reply_message=InternalErrorMessage(ex=exception),
        )

    def format_parse_exception(self, message_bus, message, event, data, exception):
        message_bus.reply_message(
            message=message,
            reply_message=InternalErrorMessage(ex=exception),
        )
