from django.contrib.auth.models import User, Permission
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .fields import AutoCreatedField, AutoLastModifiedField
from django.contrib.contenttypes.models import ContentType


class OperationalTable(models.Model):

    created = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User, related_name="+")
    last_updated = models.DateTimeField(auto_now_add=True, auto_now=True)
    last_updated_by = models.ForeignKey(User, related_name="+")
    is_active = models.BooleanField(default=True)

    class Meta:
        abstract = True


class TimeStampedModel(models.Model):
    """
    An abstract base class model that provides self-updating
    ``created`` and ``modified`` fields.
    """

    created = AutoCreatedField(_("created"))
    modified = AutoLastModifiedField(_("modified"))

    class Meta:
        abstract = True


class GlobalPermissionManager(models.Manager):
    def get_query_set(self):
        return (
            super(GlobalPermissionManager, self)
            .get_query_set()
            .filter(content_type__name="global_permission")
        )


class GlobalPermission(Permission):
    """A global permission, not attached to a model"""

    objects = GlobalPermissionManager()

    class Meta:
        proxy = True

    def save(self, *args, **kwargs):
        ct, created = ContentType.objects.get_or_create(
            name="global_permission", app_label=self._meta.app_label
        )
        self.content_type = ct
        super(GlobalPermission, self).save(*args, **kwargs)
