import bustoken
import json
import sysactions
from msgbus import TK_SYS_ACK
from typing import Dict

from model.customexception import MessageBusError
from model.productmanager import PartWithDependencies

TK_SLCTRL_PMGR_GET_PARTS_WITH_DEPENDENCIES = bustoken.create_token(
    priority=bustoken.MSGPRT_LOW,
    message_grourp="9",
    number="1",
)


class ProductManager(object):
    _parts_with_dependencies_cache = None

    @staticmethod
    def get_parts_with_dependencies():
        # type: (...) -> Dict[int, PartWithDependencies]

        if ProductManager._parts_with_dependencies_cache is not None:
            return ProductManager._parts_with_dependencies_cache

        msg = sysactions.send_message("ORDERMGR", TK_SLCTRL_PMGR_GET_PARTS_WITH_DEPENDENCIES)

        if msg.token != TK_SYS_ACK:
            raise MessageBusError(
                component="ORDERMGR",
                token=msg.token,
                data=msg.data
            )

        json_dict = json.loads(msg.data.decode("utf-8"))
        ret = {}
        for part_code, part in json_dict.items():
            part_code = int(part_code)
            ret[part_code] = PartWithDependencies(
                part_code=part_code,
                name=part["name"],
                dependencies=part["dependencies"],
            )

        ProductManager._parts_with_dependencies_cache = ret
        return ret
