# (c) cavaliba.com - data - field - file
# V3.19

"""
FieldFile: dataformat "file". Value is a list of DataFile UUID(s); the actual
upload/binding to a DataFile object happens in merge_request().

Method inventory: __init__, get_datapoint_ui_detail, get_datapoint_ui_edit,
merge_request, is_valid.
"""

from app_data.filestore import datafile_from_uploaded, uuids_to_queryset

from .field import Field


# -------------
# FILE
# -------------
class FieldFile(Field):
    def __init__(self, fieldname, fieldschema, alljson):
        """Like Field.__init__, plus file_uploaded/datafile slots populated by merge_request()."""
        super().__init__(fieldname, fieldschema, alljson)
        self.file_uploaded = None  # Django FileUploaded Object
        self.datafile = None  # DataFile object if bound

    def get_datapoint_ui_detail(self):
        """Detail datapoint with value=[uuid] plus a "queryset" of matching DataFile objects."""
        datapoint = super().get_datapoint_ui_detail()
        if len(self.value) > 0:
            datapoint["queryset"] = uuids_to_queryset(self.value)
            datapoint["value"] = self.value  # [uuid]
        else:
            datapoint["queryset"] = []
            datapoint["value"] = []

        return datapoint

    def get_datapoint_ui_edit(self):
        """Edit datapoint with value=[uuid] plus a "queryset" of matching DataFile objects."""
        datapoint = super().get_datapoint_ui_edit()
        if len(self.value) > 0:
            datapoint["queryset"] = uuids_to_queryset(self.value)
            datapoint["value"] = self.value  # [uuid]
        else:
            datapoint["queryset"] = []
            datapoint["value"] = []

        return datapoint

    def merge_request(self, request):
        """Bind an uploaded file (creating a DataFile) or keep the current selection;
        sets self.value to [fileid] or []."""

        # current selected file (from invalid > edit continu'd)
        attribute = f"current-{self.fieldname}"
        try:
            current = request.POST.get(attribute, None)
        except Exception:
            return

        # form field with file: name="file-{{ item.fieldname}}"
        attribute = f"file-{self.fieldname}"
        try:
            self.file_uploaded = request.FILES.get(attribute, None)
        except Exception:
            return

        if self.file_uploaded:
            # create DataFile object & set field value to the DataFile uuid
            self.datafile = datafile_from_uploaded(self.file_uploaded)
            if self.datafile:
                self.value = [self.datafile.fileid]
            else:
                self.value = []
        else:
            if current:
                self.value = [current]
            else:
                self.value = []

        return

    def is_valid(self):
        """Cardinality check only (super); no file-specific validation yet."""
        r = super().is_valid()

        return r
