from pathlib import Path
from .doctsobjecttyperelation import DocTsObjectTypeRelation
import fetchx.ioutils as ioutils


class DocTsTimeUnit(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def __str__(self) -> str:
        """
        Return string representation of the time unit
        """
        # Get the code and name of the time unit
        result = self.get('code','--')
        name = self.get('name',{})
        if isinstance(name, dict):
            name = name.get('en','--')
        else:
            name = '--'
        result += f' ({name})'
        return result

    @staticmethod
    def load_from_directory(base_path: Path) -> dict[str, 'DocTsTimeUnit']:
        """
        Load all Time Series Time Units from the specified directory.
        :param base_path: Base path where the metamodel is located.
        :return: A dictionary mapping time unit codes to DocTsTimeUnit instances.
        """
        result = {}
        tstype_path = base_path / "metamodel/tsTimeUnit"
        # Load all .json files
        files, directories = ioutils.search_folder(str(tstype_path.resolve()), list_of_extensions=[".json"])
        for file in files:
            value = ioutils.load_json(file)
            code = Path(file).stem
            result[code] = DocTsTimeUnit(value)
        return result
        