from re import search

from MARTe.StandardParser import logging


class ConfigDB:
    def __new__(cls):
        if not hasattr(cls, "instance"):
            cls.instance = super(ConfigDB, cls).__new__(cls)
        return cls.instance

    def __init__(self):
        ConfigDB.__INST__ = self
        self.__db__ = {}

    def get(self, path: str):
        ipath = path.split(".")
        obj = self.__db__
        for p in ipath:
            if p in obj:
                obj = obj[p]
            else:
                logging.error(f"no key {p} found for {path}")
                return None
        return obj

    def insert(self, key: dict, obj):
        pass


class MARTeOBJ:
    def __init__(self, fname, id, cfg):
        self.__name__ = id
        self.__mcls__ = cfg["Class"]
        self.__struct__ = {}
        for key, itm in cfg.items():
            if key != "Class":
                if isinstance(itm, dict) and "Class" in itm:
                    self.__struct__[key] = MARTeOBJ(fname, key, itm)
                else:
                    self.__struct__[key] = itm

    def pretty_print(self, spacing=""):
        str = f"{spacing}{self.__name__}[{self.__mcls__}]:\n"
        for key, itm in self.__struct__.items():
            if isinstance(itm, MARTeOBJ):
                str += itm.pretty_print(spacing + "  ")
            else:
                str += f"{spacing}  {key}: {itm}\n"
        return str

    def __repr__(self) -> str:
        str = f"{self.__name__}[{self.__mcls__}]:\n"
        for key, itm in self.__struct__.items():
            str += f"  {key}: {itm}\n"
        return str


def parse_config(fname: str, config: dict):
    for key, obj in config.items():
        ConfigDB().insert(key, obj)
