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

"""
FieldDate: dataformat "date", values are 'YYYY-MM-DD' strings.

Method inventory: merge_import, is_valid.
"""

import datetime

from .field import Field


# -------------
# DATE
# -------------
class FieldDate(Field):
    # 'YYYY-MM-DD'

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

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