import smtk
import smtk.attribute


class CardFormat:
    '''Formatter for individual lines in input files

    '''

    def __init__(self, att: smtk.attribute.Attribute, keyword: str, item_path: str = None, default: any = None, fmt: str = None):
        """"""
        self.keyword = keyword
        self.att = att
        self.item_path = keyword if item_path is None else item_path
        self.default = None
        self.format = fmt

    def to_string_tuple(self):
        """Returns (keyword, value) string pair, or None if not relevant."""
        item = self.att.itemAtPath(self.item_path, '/', activeOnly=True)
        if item is None:
            t = None if self.default is None else (self.keyword, self.default)
            return t

        # Future: check categories

        if not item.isEnabled():
            return None

        if not item.isSet():
            return None

        if not hasattr(item, 'value'):
            t = None if self.default is None else (self.keyword, self.default)
            return t

        format = self.format
        if format is None:
            format = '%g' if item.type() == smtk.attribute.Item.DoubleType else '%s'
        value = format % item.value()
        return (self.keyword, value)
