from typing import List

from event_manager_api.shared import token, SubscriptionInfoDto, AddressDto
from event_manager_api.shared.exception import UnknownError
from event_manager_api.shared.token import TK_EVENT_MANAGER_SUBSCRIBE
from messagebus import MessageBus, Message, DataType, DefaultToken


class EventManager(object):
    def __init__(self, message_bus: MessageBus):
        self.message_bus = message_bus

    def subscribe(
        self,
        service_name: str,
        subjects: List[str],
        subscription_id: str = "",
    ):
        subjects_data = b""
        for subject in subjects:
            subjects_data += subject.encode() + b"\0"

        subjects_data = subjects_data[:-1]
        data = subscription_id.encode() + b"\0" + service_name.encode() + b"\0" + subjects_data

        reply = self.message_bus.send_message(
            component=token.component_name,
            message=Message(
                token=TK_EVENT_MANAGER_SUBSCRIBE,
                data_type=DataType.param,
                data=data,
            ),
        )

        if reply.token != DefaultToken.TK_SYS_ACK:
            raise UnknownError(
                token=reply.token,
                data=reply.data,
            )

        reply_parts = reply.data.split(b"\0")

        pub_address = reply_parts[1].decode()
        sub_address = reply_parts[2].decode()
        return SubscriptionInfoDto(
            subscription_id=reply_parts[0].decode(),
            pub_address=AddressDto.build_from_str(address=pub_address),
            sub_address=AddressDto.build_from_str(address=sub_address),
        )
