from typing import List

import safe_radix32
from clarabot_crypto.group_config.block import GroupConfigBlock
from clarabot_crypto.group_config.chain import GroupConfigBlockChain

from clarabot_nano.core.config.utility import block_name_to_config_format
from clarabot_nano.utility.serialize import msgpack_loads


def room_blocks_from_room_data(room_data) -> List[str]:
    return [
        block_name_to_config_format(
            GroupConfigBlockChain.create_block_name(parse_raw_for_block_name(room_data["_config_blocks"][-1][1]))
        ),
    ]


def parse_raw_for_block_name(raw_block) -> dict:
    block = msgpack_loads(raw_block)
    return assemble_for_block_name(
        safe_radix32.decode(block[GroupConfigBlock.BLOCK_ID]),
        GroupConfigBlockChain.create_block_hash(block, raw_block),
    )


def parse_components_for_block_name(block_id: int, block_hash: bytes) -> str:
    return block_name_to_config_format(
        GroupConfigBlockChain.create_block_name(assemble_for_block_name(block_id, block_hash))
    )


def assemble_for_block_name(block_id: int, block_hash: bytes) -> dict:
    return {GroupConfigBlock.BLOCK_ID: block_id, GroupConfigBlock.OWN_HASH: block_hash}
