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

from app_data.permissions import permission_get_by_name
from app_user.models import SirenePermission

from .field import Field


# -------------
# PERMISSION
# -------------
class FieldPermission(Field):
    def get_attribute(self):
        """
        return list of SirenePermission object
        """
        # self.value = ["a", "b", ..."]

        reply = []

        for pname in self.value:
            obj = permission_get_by_name(pname)
            reply.append(obj)
        return reply

    def get_datapoint_ui_detail(self):

        datapoint = super().get_datapoint_ui_detail()
        datapoint["value"] = []
        perms = SirenePermission.objects.filter(keyname__in=self.value)
        for i in perms:
            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)

        return datapoint

    def get_datapoint_ui_edit(self):

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

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

        perms = SirenePermission.objects.all()
        for i in perms:
            if i.keyname in self.value:
                selected = True
            else:
                selected = False
            item = {"key": i.keyname, "display": i.displayname, "selected": selected}
            datapoint["value"].append(item)

        return datapoint

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