from typing import (
    Dict,
    List,
    Optional,
    Union,
)

from messagebus import (
    AckMessage,
    InternalErrorMessage,
    NakMessage,
)
from messageprocessorutil import UuidMessageProcessor


class GetConfigProcessor(UuidMessageProcessor):
    def __init__(self, config_dict: Dict[str, Union[str, List[str]]]) -> None:
        super().__init__()
        self.store_config = config_dict

    def parse_data(self, data: bytes) -> str:
        return data.decode()

    def call_business(self, key_path: str) -> Optional[Union[str, List[str]]]:
        return self.store_config.get(key_path)

    def format_response(
        self,
        message_bus,
        message,
        event,
        key_path,
        value,
    ):
        if value is None:
            reply = NakMessage()
        else:
            ret = value
            if isinstance(value, list):
                ret = "\0".join(value)

            reply = AckMessage(data=ret.encode())

        message_bus.reply_message(
            message=message,
            reply_message=reply,
        )

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