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

from .field import Field

#from app_user.group import group_all_filtered
#from app_user.group import group_get_by_name

from app_user.models import SireneGroup




def group_all_filtered(is_enabled=None, filter=None):
    # prefetch_related('').
    if is_enabled:
        return SireneGroup.objects.filter(is_enabled=True, is_role=False).all()
    else:
        return SireneGroup.objects.filter(is_role=False).all()

def group_get_by_name(name):
    return SireneGroup.objects.filter(keyname=name, is_role=False).prefetch_related('users').first()

# -------------
# GROUP
# -------------
class FieldGroup(Field):


    def get_attribute(self):

        reply = []
        for groupname in self.value:
            groupobj = group_get_by_name(groupname)
            reply.append(groupobj)
        return reply


    def get_datapoint_ui_detail(self):
        
        datapoint = super().get_datapoint_ui_detail()
        datapoint["value"] = []
        groups = SireneGroup.objects.filter(keyname__in=self.value, is_role=False)
        for i in groups:
            if i.displayname and len(i.displayname) > 0:
                dn = i.displayname
            else:
                dn = i.keyname
            item = { "key":i.keyname, "display":dn, "id":i.id }
            datapoint["value"].append(item)

        # try:
        #     #datapoint["value"] = ', '.join(self.value)
        #     datapoint["value"] = self.value
        # except:
        #     datapoint["value"] = ''
        return datapoint        


    def get_datapoint_ui_edit(self):

        # value: [ { 'key':'keyname' , 'selected':True/False }, ...    ]

        datapoint = super().get_datapoint_ui_edit()
        datapoint["value"] = self.value
        datapoint["value"] = []

        all_instances_obj = group_all_filtered()

        for i in all_instances_obj:
            if i.keyname in self.value:
                selected = True
            else:
                selected = False
            item = { "key":i.keyname, "selected":selected}
            datapoint["value"].append( item )

        return datapoint        


    def is_valid(self):
        r = super().is_valid()
        # TODO
        return r