from django.db import models
from django.db.models import Model


class Subject(Model):
    subject_id = models.AutoField(primary_key=True)

    def _get_real_instance(self):
        """Downcast to the actual subclass instance (UserSubject or UserGroupSubject)."""
        for attr in ("usersubject", "usergroupsubject"):
            try:
                return getattr(self, attr)
            except (self.__class__.DoesNotExist, self.DoesNotExist):
                pass
            except AttributeError:
                pass
        return self

    def _get_subject_type(self):
        real = self._get_real_instance()
        if real is not self:
            return real._get_subject_type()
        raise NotImplementedError()

    def add_perms(self, restricted_object, perm, source):
        real = self._get_real_instance()
        if real is not self:
            return real.add_perms(restricted_object, perm, source)
        raise NotImplementedError()

    def _get_user_subjects(self):
        real = self._get_real_instance()
        if real is not self:
            return real._get_user_subjects()
        raise NotImplementedError()
