from django.db import models
from django.conf import settings
from crum import get_current_user
from django.contrib.auth.models import AnonymousUser
from .manager import SoftDeleteManager


class BaseModel(models.Model):
    create_date = models.DateTimeField(auto_now_add=True)
    modify_date = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="%(class)s_createddby",  # noqa
        null=True,
        blank=True,
    )
    modified_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="%(class)s_modifiedby",  # noqa
        null=True,
        blank=True,
    )
    creator_info = models.CharField(max_length=100, null=True)
    modifier_info = models.CharField(max_length=100, null=True)
    trash = models.BooleanField(default=False)
    objects = SoftDeleteManager()  # filter all records with trash=False
    all_objects = SoftDeleteManager().all_with_deleted()  # get all records

    def soft_delete(self):
        self.trash = True
        self.save(update_fields=['trash'])

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        user = get_current_user()  # get user object
        if not isinstance(user, AnonymousUser):
            self.modified_by = user
            if not self.creator_info:
                self.created_by = user
                self.creator_info = user.first_name + ' ' + user.last_name
            self.modifier_info = user.first_name + ' ' + user.last_name
        super(BaseModel, self).save(*args, **kwargs)


class MobileTest(BaseModel):
    latitude = models.DecimalField(max_digits=22, decimal_places=16)
    longitude = models.DecimalField(max_digits=22, decimal_places=16)
    count = models.IntegerField(default=0)
    time = models.DateTimeField(auto_now_add=True)


class SystemConfig(BaseModel):
    key = models.CharField(max_length=100, null=True)
    value = models.CharField(max_length=100, null=True)

    @classmethod
    def get(cls, key, default=None):
        try:
            return cls.objects.get(key=key).value
        except cls.DoesNotExist:
            return default
