# (c) cavaliba.com - data - field - role
# 3.21.0

from .field import Field

#from app_user.role import role_all_filtered
#from app_user.role import role_get_by_name

from app_user.models import SireneGroup


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

def role_get_by_name(name, enabled_only=False):

    if enabled_only:
        return SireneGroup.objects.filter(keyname=name, is_role=True, is_enabled=True)\
            .prefetch_related('users')\
            .prefetch_related('subgroups')\
            .prefetch_related('permissions')\
            .first()
    else:
        return SireneGroup.objects.filter(keyname=name, is_role=True)\
            .prefetch_related('users')\
            .prefetch_related('subgroups')\
            .prefetch_related('permissions')\
            .first()


# -------------
# ROLE
# -------------
class FieldRole(Field):


    def get_attribute(self):

        reply = []
        for rolename in self.value:
            roleobj = role_get_by_name(rolename)
            reply.append(roleobj)
        return reply


    def get_datapoint_ui_detail(self):
        
        datapoint = super().get_datapoint_ui_detail()
        datapoint["value"] = []
        roles = SireneGroup.objects.filter(keyname__in=self.value, is_enabled=True, is_role=True)
        for i in roles:
            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 = role_all_filtered(is_enabled=True)

        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