# util functions for all apps
from django.contrib.admin.models import ADDITION, CHANGE, LogEntry
from django.contrib.admin.utils import construct_change_message
from django.contrib.contenttypes.models import ContentType


def add_log_action(request, form, app_label, model, add=True):
    obj = form.save()
    content_type = ContentType.objects.get(app_label=app_label, model=model)
    change_message = construct_change_message(form, None, add)

    if add:
        action_flag = ADDITION
    else:
        action_flag = CHANGE

    LogEntry.objects.log_action(
        user_id=request.user.pk,
        content_type_id=content_type.pk,
        object_id=obj.pk,
        object_repr=str(obj),
        action_flag=action_flag,
        change_message=change_message,
    )
