from typing import Tuple

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


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

    def parse_data(self, data: bytes):
        service_type, service_name, address, port = data.decode().split("\0")
        port = int(port)
        return service_type, service_name, address, port

    def call_business(self, request: Tuple[str, str, str, int]):
        service_type, service_name, address, port = request
        self.service_locator.register(
            service_type=service_type,
            service_name=service_name,
            address=address,
            port=port,
        )

    def format_response(self, message_bus, message, event, input_obj, result):
        message_bus.reply_message(
            message=message,
            reply_message=AckMessage(),
        )

    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),
        )
