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

import time

from .field import Field
from app_data.filestore import datafile_from_uploaded
from app_data.filestore import uuids_to_filenames
from app_data.filestore import uuids_to_queryset


# -------------
# FILE
# -------------
class FieldFile(Field):

    def __init__(self, fieldname, fieldschema, alljson):
        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):
        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):
        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):
                   
        # current selected file (from invalid > edit continu'd)
        attribute = f"current-{self.fieldname}"
        try:
            current = request.POST.get(attribute,None)
        except:
            return

        # form field with file: name="file-{{ item.fieldname}}"
        attribute = f"file-{self.fieldname}"
        try:
            self.file_uploaded = request.FILES.get(attribute, None)
        except:
            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):
        r = super().is_valid()

        return r
