from typing import Optional

from chemrecon.schema import Entry, FeatureEnum
from chemrecon.schema.db_object import Column, col_recon_id


class MolStructure(Entry):
    """ Abstract representation of a structure in SMILES format.
    """
    # Attributes
    smiles: str  #: The canonical SMILES identifier.
    std_feats: Optional[list[FeatureEnum]]  #: The features w.r.t which this structure is standardized (see TODO).
    molformula: Optional[str]  #: The sum formula.

    # Database
    entrytype_name = 'MolStructure'
    _table_name = 'MolStructure'
    _columns = [
        col_recon_id,
        Column('smiles', str, index_hash = True),
        Column('std_feats', list[FeatureEnum]),
        Column('molformula', str),
    ]
    _index = [1]

    # Visualisation
    _draw_colour = '00FFFF'

    def __init__(
        self,
        smiles: str,
        std_feats: Optional[list[FeatureEnum]] = None,
        molformula: Optional[str] = None,
        recon_id: Optional[int] = None,
    ):
        super().__init__(recon_id)
        self.smiles = smiles
        self.std_feats = std_feats
        self.molformula = molformula

        # Calculate std. features if none
        if self.std_feats is None:
            from chemrecon import mol_from_smiles
            mol = mol_from_smiles(smiles = self.smiles)
            self.std_feats = {feat.feature_enum for feat in mol.features}

        # Calculate sum formula if not given
        if self.molformula is None:
            # TODO
            pass

    def _vis_str(self) -> str:
        return f'{self.smiles}\n({self._feat_str()})'

    def _feat_str(self) -> str:
        if self.std_feats is None:
            return '?'
        s: str = ''
        s += 'F,' if FeatureEnum.F in self.std_feats else '-,'
        s += 'I,' if FeatureEnum.I in self.std_feats else '-,'
        s += 'C,' if FeatureEnum.C in self.std_feats else '-,'
        s += 'T,' if FeatureEnum.T in self.std_feats else '-,'
        s += 'S,' if FeatureEnum.S in self.std_feats else '-,'
        return s
