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


from datetime import timedelta

from django.utils import timezone

from app_data.models import DataRevision
from app_home.configuration import get_configuration


# 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 Exception:
        classname = ""

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

    try:
        displayname = instance.displayname
    except Exception:
        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, displayname=None, action="edit"
):

    if aaa:
        username = aaa.get("username", "auto")
    try:
        revobj = DataRevision(
            classname=classname,
            keyname=keyname,
            displayname=displayname or "",
            username=username,
            action=action,
        )
        revobj.save()
    except Exception:
        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 Exception:
        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
