from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.urls import reverse
from django.db import transaction
from django.core.paginator import Paginator

from django.db.models import Q

from .models import Item, UOM
from .forms import ItemForm, PriceLevelForm

from django.db.models import Q
from Item.models import Item, PriceLevel, PriceLevelItem
import json

def index_pricelevel(request):
    context={}
    context['objects']=PriceLevel.objects.order_by('Name')
    context['addurl'] = reverse('Item:add_pricelevel')
    # print(context['objects'])
    return render(request, "Item/index_pricelevel.html", context=context)

def add_pricelevel(request, id=None):
    context={}
    # print(f"idroot={id}")
    pricelevel1 = None
    plname=None
    context['pk'] = 'null'
    if id:
        print(f"edit id={id}")
        pricelevel1=get_object_or_404(PriceLevel, pk=id)
        plname= pricelevel1.Name
        print(plname)
        context['pk'] = pricelevel1.pk
    else:
        print("add new")

    form = PriceLevelForm(request.POST or None, instance=pricelevel1)
    qs1 = Item.objects.filter(itempricelevel__PL__Name=plname).prefetch_related("itempricelevel").values('FullName','SalesPrice', 'itempricelevel__Price')
    qs2 = Item.objects.exclude(itempricelevel__PL__Name=plname).prefetch_related("itempricelevel").values( "FullName", "SalesPrice", "AlwaysNull")
    # print(qs2)
    qs = qs1.union(qs2)
    # print(type(qs))
    # print(qs)
    context['objects'] = qs
    context['form'] = form
    if request.POST:
        datas = request.POST.get('data')
        pk = request.POST.get('pk')
        print(pk)
        with transaction.atomic():
            if form.is_valid():
                print(form.cleaned_data["Name"])
                pricelevel = form.save()
                print("form pricelevel saved")
                # return redirect(reverse("index"))
            else:
                print("form not valid")
                return render(request, "Item/addedit_pricelevel.html", context=context)

            # pricelevel = get_object_or_404(PriceLevel, pk=pk)

            # print(f"pk={pk}; object={pricelevel}")
            # print(type(datas))
            # print(datas)
            datas = json.loads(datas)
            # print(type(datas))
            # print(datas)
            # print(form["Name"].value())
            blAllSaved = True
            if len(datas)>0:
                print("more than 0")
                for data in datas:
                    print(type(data))
                    print(data)
                    # print(data['FullName'])
                    if data['dtchange']=="1" or data['dtchange']=="2":
                        ## add new pricelevelitem
                        print("dtchange 1,2")
                        item = get_object_or_404(Item, FullName = f"{data['FullName']}")
                        print(f"object=={item}")
                        pricelevelitem, created = PriceLevelItem.objects.get_or_create(PL=pricelevel, IPL=item, defaults={'Price':data['price']})
                        print(f"created={created}")
                        print(f"object=={pricelevelitem}")
                        if not created:
                            pricelevelitem.Price = data['price']
                            pricelevelitem.save()
                        print(f"object=={pricelevelitem}")
                    else:
                        blAllSaved=False
                        print("dtchange is NOT 1 or 2")
                if blAllSaved:
                    return redirect(reverse('Item:index_pricelevel'))
                else:
                    return redirect(reverse('Item:edit_pricelevel', pricelevel.pk ))
            else:
                return redirect(reverse('Item:index_pricelevel'))
    return render(request, "Item/addedit_pricelevel.html", context=context)

def edit_pricelevel(request, pk):
    context={}
    qs1 = Item.objects.filter(itempricelevel__PL__Name='B2020',).prefetch_related("itempricelevel").values('FullName','SalesPrice', 'itempricelevel__Price')
    qs2 = Item.objects.exclude(itempricelevel__PL__Name='B2020').prefetch_related("itempricelevel").values( "FullName", "SalesPrice", "AlwaysNull")
    # print(qs2)
    qs = qs1.union(qs2)
    # print(type(qs))
    # print(qs)
    context['objects'] = qs
    return render(request, "Item/addedit_pricelevel.html", context=context)



def index(request):
    context={}
    search = request.GET.get("q")
    items=Item.objects.all().order_by('FullName')
    if search:
        item = Item.objects.order_by('FullName').filter(Q(Name__icontains=search) | Q(FullName__icontains=search))
    else:
        item = Item.objects.order_by('FullName')
    paginator = Paginator(item, 25)  # Show 25 contacts per page.
    page_number = request.GET.get("page")
    page_obj = paginator.get_page(page_number)
    # heads = [f.name for f in Item._meta.get_fields()]
    # print(heads)
    context['objects'] = page_obj
    context['items'] = items
    context['addurl'] = reverse('Item:add_item')
    return render(request, "Item/index.html", context=context)


def add_item(request):
    form = ItemForm(request.POST or None)
    if request.POST:
        print(form["Name"].value())
        if form.is_valid():
            print(form.cleaned_data["Name"])
            form.save()
            return redirect(reverse("Item:index"))
    print(form["Name"].value())
    return render(request, "Item/addedit_item.html", {"form":form})


def delete_item(request, pk):
    item = get_object_or_404(Item, pk=pk)
    item.delete()
    return HttpResponse(f"{pk} is deleted")


def edit_item(request, pk):
    print(pk)
    print(request)
    item = get_object_or_404(Item, pk=pk)
    form = ItemForm( request.POST or None, instance=item)
    if request.method == "GET":
        print("GET")
        if item:
            # form = ItemForm(instance=item)
            return render(request, "Item/addedit_item.html", {"objects": [item,], "form":form})
    elif request.method == "POST":
        print("POST")
        # form = ItemForm(request.POST, instance=item)
        if form.is_valid():
            print("form is valid")
            item=form.save()
            # return redirect(reverse('Item:edit_item', kwargs={"pk":pk}))
            return render(request, "Item/index.html", {"objects": [item]})
        else:
            print("not valid form")
            return render(request, "Item/addedit_item.html", {"objects": [item,], "form":form})
