from typing import Optional

from messagebus import (
    AckMessage,
    ApplicationErrorMessage,
    BadRequestMessage,
    NakMessage,
)
from messageprocessorutil import UuidMessageProcessor
from service_locator_api.shared.error import (
    CodedError,
    LocateError,
)
from .._ServiceLocator import ServiceLocator


class LocateServiceProcessor(UuidMessageProcessor):

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

    def parse_data(self, data):
        try:
            service_name = data.decode("utf-8")
        except UnicodeDecodeError:
            raise LocateError.INVALID_SERVICE_NAME

        return service_name

    def call_business(self, service_name: str) -> Optional[str]:
        return self.service_locator.locate_service(service_name)

    def format_response(self, message_bus, message, 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=message,
                reply_message=ApplicationErrorMessage(
                    error_code=LocateError.SERVICE_NOT_FOUND.code,
                    error_message=LocateError.SERVICE_NOT_FOUND.message,
                )
            )

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

    def format_parse_exception(self, message_bus, message, data, exception):
        if isinstance(exception, CodedError):
            message_bus.reply_message(
                message=message,
                reply_message=BadRequestMessage(
                    error_code=exception.code,
                    error_message=exception.message,
                )
            )
        else:
            message_bus.reply_message(message, NakMessage(str(exception).encode("utf-8")))
