# (c) cavaliba.com - data - field - time

"""
FieldTime: dataformat "time", values are 'hh:mm:ss' strings.

Method inventory: merge_import, is_valid.
"""

import datetime

from .field import Field


# -------------
# TIME
# -------------
class FieldTime(Field):
    # 'hh:mm:ss'

    def merge_import(self, data):
        """Set self.value from an import/API payload, keeping only 8-char strings
        (no split_composite)."""
        # no split composite !
        self.value = []
        if type(data) is str:
            if len(data) == 8:
                self.value = [data]
        elif type(data) is list:
            for i in data:
                if type(i) is str and len(i) == 8:
                    self.value.append(i)

    def is_valid(self):
        """Cardinality check (super) plus: every value must parse as %H:%M:%S."""
        r = super().is_valid()
        for v in self.value:
            if type(v) is str:
                if len(v) != 8:
                    return False
            try:
                timeformat = "%H:%M:%S"
                _nouse = datetime.datetime.strptime(v, timeformat)
            except Exception:
                return False
        return r
