from django.db import models

from topdownrbac.models import Subject
from topdownrbac.models.subjecttype import SubjectType


class UserGroupSubject(Subject):
    user_subjects = models.ManyToManyField("topdownrbac.UserSubject", related_name="user_group_subjects")

    def _get_subject_type(self):
        return SubjectType.GROUP

    def _get_user_subjects(self):
        return self.user_subjects.all()

    def add_user(self, user_subject):
        self.user_subjects.add(user_subject)
        from topdownrbac.models import RoleBinding

        for role_binding in RoleBinding.objects.filter(subject_id=self.subject_id):
            role_binding._add_all_perms_to_single_user_subject(user_subject)

    def remove_user(self, user_subject):
        self.user_subjects.remove(user_subject)
        from topdownrbac.models import RoleBinding

        for role_binding in RoleBinding.objects.filter(subject_id=self.subject_id):
            role_binding._remove_all_perms_from_single_user_subject(user_subject)
