from django.shortcuts import render

from app.entities import models
from app.applicationlayer import paginators

from datetime import datetime

from rest_framework.response import Response
from rest_framework import status, views

from rest_framework.decorators import action
from django.http import Http404

from django.db.models import Q
from app.applicationlayer.cms.utils_cr import (
    number_generator, crhistory_save, entity_log_bulk
)
from app.applicationlayer.utils import model_to_dict
from app.entities import enums, models
from app.applicationlayer.utils import log_save, CustomPagination
from app.applicationlayer.cms.template import serializers


def tmp_add_edit_delete(tmp_request_body,
                        queryset,
                        enum_type,
                        serializer_data,
                        partial,
                        self,
                        template_no):
    
    # delete ids not in request body
    request_ids = [i['id'] for i in tmp_request_body if "id" in i]

    delete_query = queryset.objects.filter(
        template_no=template_no
    ).exclude(
        id__in=request_ids
    )

    if delete_query.count() > 0:
        entity_log_bulk(
            delete_query,
            enum_type,
            queryset
        )

    # update or create
    for i in tmp_request_body:
        if "id" in i:
            tmp_instance = queryset.objects.get(
                pk=i['id']
            )
            tmp_code = {
                "template_no": template_no
            }
            data = {**i, **tmp_code}
            
            serializer = serializer_data(tmp_instance,
                                         data=data,
                                         partial=partial)

            serializer.is_valid(raise_exception=True)
            old_instance = model_to_dict(tmp_instance)
            
            self.perform_update(serializer)
            new_instance = serializer.data
            
            log_save(
                enums.LogEnum.UPDATE.value,
                enum_type,
                i['id'],
                old_instance,
                new_instance
            )
        else:
            tmp_code = {
                "template_no": template_no
            }
            data = {**i, **tmp_code}
            serializer = serializer_data(data=data)
            serializer.is_valid(raise_exception=True)

            self.perform_create(serializer)
            new_instance = serializer.data
            try:
                log_save(
                    enums.LogEnum.ADD.value,
                    enum_type,
                    old_instance['id'],
                    '',
                    new_instance
                )
            except Exception as e:
                log_save(
                    enums.LogEnum.ADD.value,
                    enum_type,
                    new_instance['id'],
                    '',
                    new_instance
                )

    return True
