from pathlib import Path
import fetchx.ioutils as ioutils
from .doctemplates import Palette, use_template


class DocTsObjectTypeRelation(dict):
    def __init__(self, *args, **kwargs):
        """
        Represents a Time Series Object Type Relation in the metamodel.
        Inherits from dict to store relation properties.
        """
        super().__init__(*args, **kwargs)
        self.source_tsobjecttype = None  # type: DocTsObjectType | None
        self.target_tsobjecttype = None  # type: DocTsObjectType | None
        self._html: str | None = None  # type: str | None

    @staticmethod
    def load_from_directory(base_path: Path) -> dict[str, 'DocTsObjectTypeRelation']:
        """
        Load all Time Series Object Type Relations from the specified directory.
        :param base_path: Base path where the metamodel is located.
        :return: A dictionary mapping relation codes to DocTsObjectTypeRelation instances.
        """
        result = {}
        tsobjecttyperelations_path = base_path / "metamodel/tsObjectTypeRelation"
        # Load all .json files
        files, directories = ioutils.search_folder(str(tsobjecttyperelations_path.resolve()), list_of_extensions=[".json"])
        for file in files:
            value = ioutils.load_json(file)
            code = Path(file).stem
            result[code] = DocTsObjectTypeRelation(value)
        return result    
    
    def to_string(self, language: str = "en") -> str:
        """
        Convert the Time Series Object Type to a string representation.
        :param language: Language code for localization.
        :return: String representation of the Time Series Object Type.
        """
        if self._html is not None:
            return self._html
        result = ""
        # generate tsobjecttype for specific language, e.g., 'en'
        result += use_template('TSObjectTypeRelation_Begin', {'TSObjectTypeRelationCode': self.get("code", "--")}, language=language)
        # Generate footer content
        footer_content = ""
        footer_content += f'<strong>Value Provider Type: </strong>{self.get("valueProviderType", "--")}, '
        footer_content += f'<strong>Value Provider API: </strong>{self.get("valueProviderApi", "--")}'
        # generate block with border color from parent tsobjecttype
        result += use_template('TSObjectTypeRelation_Block',{
            'border_color': self.source_tsobjecttype.color if self.source_tsobjecttype is not None else "grey",
            'footer': footer_content,
            'TSObjectTypeRelationCode':self.get('code','--'),
            'color_scheme': 'yellow' if self.get("valueProviderType", "--") != 'mapping' else 'grey'
            }, language=language
        ) # type: ignore
        result += use_template('TSObjectTypeRelation_BlockSectionStart', {}, language=language)
        # generate block content
        result += use_template('TSObjectTypeRelation_BlockContent',{
            'name': self.get('name', '--'),
            'short_name': self.get('shortName', '--'),
            'description': self.get('desc', '--'),
            'relation_type': self['sourceCardinality'] + " to " + self['targetCardinality'],
            'source_tsobjecttype_link': f'#{self.source_tsobjecttype["code"]}', # type: ignore
            'source_tsobjecttype': self.source_tsobjecttype['code'] if self.source_tsobjecttype is not None else "--",
            'target_tsobjecttype_link': f'#{self.target_tsobjecttype["code"]}', # type: ignore
            'target_tsobjecttype': self.target_tsobjecttype['code'] if self.target_tsobjecttype is not None else "--"
            }, language=language
        )
        result += use_template('TSObjectTypeRelation_End', {}, language=language)
        self._html = result
        return result
        