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


class SubscribeProcessor(UuidMessageProcessor):
    def __init__(self, event_manager: EventManager):
        super().__init__()
        self.event_manager = event_manager

    def parse_data(self, data: bytes):
        parts =  data.decode().split("\0")
        return {
            "subject": parts[0],
            "address": parts[1],
            "port": int(parts[2]),
        }

    def call_business(self, service_name):
        return self.event_manager.subscribe(
            service=Service(
                type="",
                name="",
                address=service_name["address"],
                port=service_name["port"],
            ),
            subject=service_name["subject"],
        )

    def format_response(self, message_bus, message, event, service_name: str, service: Service):
        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),
        )
