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


class UnsubscribeProcessor(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")
        result = {
            "subject": parts[0],
            "address": parts[1],
            "port": int(parts[2]),
        }

        return result

    def call_business(self, service_data):
        service = Service(
            type="",
            name="",
            address=service_data["address"],
            port=service_data["port"],
        )

        if service_data["subject"] != "" :
            return self.event_manager.unsubscribe(
                service=service,
                subject=service_data["subject"],
            )
        else:
            return self.event_manager.unsubscribe_all(
                service=service,
            )

    def format_response(self, message_bus, message, event, service_data, 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),
        )
