from django.db import models
from datetime import datetime

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

# Ordering of | null=True, blank=True | is IMPORTANT!:
#
# Order 1 : null=True, blank=True
#   NULL as default value
#
# Order 2 : blank=True, null=True
#   Requires to add 'default="your_default_val_here"
#   else, it will error upon saving


'''
BaseAuditClass
  The base class that will give:
  created, createdby, updated, updatedby, deleted & deletedby COLUMNS
  to whoever inehrits it.
'''


from app.middleware.current_user.data import get_current_user


class BaseAuditClass(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    createdby = models.CharField(max_length=255)
    modified = models.DateTimeField(auto_now=True)
    modifiedby = models.CharField(max_length=255)

    def save(self, *args, **kwargs):
        if self.createdby and self.modifiedby:
            # username = 'Anonymous User'
            # self.createdby = username
            # self.modifiedby = username
            super(BaseAuditClass, self).save(*args, **kwargs)
        else:

            username = 'Anonymous User'
            user = get_current_user()

            # user.is_authenticated():

            if user and user.username:
                username = user.username

            self.modifiedby = username

            if self._state.adding:
                self.createdby = username
            super(BaseAuditClass, self).save(*args, **kwargs)

    class Meta:
        abstract = True


'''
Status Table
  Inherits BaseAuditClass
  Hence, it will get all the proterties of its parent.
  This is a standalone table.
  Purpose:
      To tag the status of all rows in a specific tables as:
          ACT - Active
          DCT - Deactivated
          DEL - Deleted
          ARC - Archived
'''


class Status(BaseAuditClass):
    ref = models.CharField(max_length=10)
    code = models.CharField(unique=True, max_length=10)
    name = models.CharField(unique=True, max_length=10)
    description = models.CharField(max_length=100, blank=False, null=True)

    def __str__():
        return self.name

    class Meta:
        db_table = 'status_set'


'''
AuditClass
  Combination of BaseAuditClass & Status.
  Extends 'BaseAuditClass' to get the auditing columns.
  References 'Status' table to attach Status to each rows of the inheriting
  table.

  This is the class who will be inherited by the tables in this project
  instead of 'models.Model' (which is the default).
'''


class AuditClass(BaseAuditClass):
    # status = models.ForeignKey(Status, on_delete=models.PROTECT)

    class Meta:
        abstract = True

    def _str__(self):
        return self.name

