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

from django.conf import settings
from .field import Field

# -------------
# BOOLEAN
# -------------
class FieldBoolean(Field):


    def __init__(self, fieldname, fieldschema, alljson):
        super().__init__(fieldname, fieldschema, alljson)

        # if no json, unpack default_value
        if not alljson:
            if self.default_value:
                ml = self.default_value.split()
                try:
                    self.value = [i in settings.TRUE_LIST for i in ml]
                except:
                    self.value = []


    def get_first_value(self):
        try:
            return self.value[0] in settings.TRUE_LIST
        except:
            return False
        
    def is_field_true(self):
        if len(self.value) == 1:
            if self.value[0] in settings.TRUE_LIST:
                return True
        return False


    def merge_request(self, request):

        data = request.POST.getlist(self.fieldname, default=[])
        self.value=[]
        if not data:
            return
        if type(data) is list:
            for i in data:
                try:
                    r = i in settings.TRUE_LIST
                    self.value.append(r)
                except:
                    pass
        else:
            try:
                r = data in settings.TRUE_LIST
                self.value.append(r)
            except:
                pass


    def merge_import(self, data):

        self.value=[]
        if type(data) is list:
            for i in data:
                r = i in settings.TRUE_LIST
                self.value.append(r)
        else:
            r = data in settings.TRUE_LIST
            self.value.append(r)


    def is_valid(self):
        r = super().is_valid()
        for b in self.value:
            if not isinstance(b, (bool)):
                return False
        return r
