# (c) cavaliba.com - data / revisio.py
# V3.23


from datetime import timedelta
from django.utils import timezone
from django.utils.translation import gettext as _

from app_home.configuration import get_configuration

from app_data.models import DataRevision


# for Data Instance objects
def revision_add(aaa=None, instance=None, action="edit"):

    if aaa:
        username = aaa.get("username", "auto")
    else:
        username = "auto"

    try:
        classname = instance.classname
    except:
        classname = ""


    try:
        keyname = instance.keyname
    except:
        keyname = ""

    try:
        displayname = instance.displayname
    except:
        displayname = ""

    revobj = DataRevision(classname=classname, keyname=keyname, displayname=displayname, username=username, action=action)
    revobj.save()


# for iam/_user/_group/_role (no Instance object)
def revision_add_raw(aaa=None, username=None, classname=None, keyname=None, action="edit"):

    if aaa:
        username = aaa.get("username", "auto")
    try:
        revobj = DataRevision(classname=classname, keyname=keyname, username=username, action=action)
        revobj.save()
    except:
        pass


# GET
def revision_get(classname=None, keyname=None, limit=None):

    if not limit:
        limit = int(get_configuration(appname="home", keyname="REVISION_DISPLAY"))

    try:
        return DataRevision.objects.filter(classname=classname, keyname=keyname).order_by("-date")[:limit]
    except:
        return []


#  PURGE
def revision_purge(aaa=None):
    count = 0
    keep_days = int(get_configuration(appname="home", keyname="REVISION_KEEP_DAYS"))
    count = DataRevision.objects.filter(date__lte=timezone.now()-timedelta(days=keep_days)).delete()[0]
    return count

