from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.template import loader, RequestContext
from django.views import View

from home.models import Customer, CustomerForm, Bill, Inventory, SupportCases, BillForm, InventoryForm, SupportCasesForm

month_list = ['Janauary',
              'February',
              'March',
              'April',
              'May',
              'June',
              'July',
              'August',
              'September',
              'October',
              'November',
              'December'
              ]

month = datetime.now().month


# Create your views here.
@login_required(login_url='/admin/login/?next=/')
def index(request, bill="all"):
    template = loader.get_template('index.html')

    customers = Customer.objects.order_by('-id')[:10]
    if bill == "due":
        print(month_list[month - 1])
        customers = Customer.objects.exclude(billed_month=month_list[month - 1])[:10]
        print('====due')
        print(customers)
    bills = Bill.objects.order_by('-bill_id')[:10]
    inventories = Inventory.objects.order_by('-item_updated')[:10]
    support_cases = SupportCases.objects.order_by('-case_id')[:10]

    context = {
        'customers': customers,
        'bills': bills,
        'inventories': inventories,
        'support_cases': support_cases,
        'bill_f': bill,
        'customer_number': customers.count()

    }
    return HttpResponse(template.render(context, request))


@login_required(login_url='/admin/login/?next=/')
def updateFields(request, entity, action="create", id=None):
    print(entity)
    print(id)
    form = None

    if action == "delete":
        if entity == "customer":
            customer = Customer.objects.filter(id=id).delete()
        if entity == "bill":
            bill = Bill.objects.filter(bill_id=id).delete()
        if entity == "inventory":
            inventory = Inventory.objects.filter(product_id=id).delete()
        if entity == "support":
            supportCase = SupportCases.objects.filter(case_id=id).delete()
        return redirect(index)
    if id is not None and entity == "customer":
        customer = Customer.objects.get(id=id)
        form = CustomerForm(instance=customer)
    if id is not None and entity == "bill":
        bill = Bill.objects.get(bill_id=id)
        form = BillForm(instance=bill)
    if id is not None and entity == "inventory":
        inventory = Inventory.objects.get(product_id=id)
        form = InventoryForm(instance=inventory)
    if id is not None and entity == "support":
        supportCase = SupportCases.objects.get(case_id=id)
        form = SupportCasesForm(instance=supportCase)

    if id is None and entity == "customer":
        form = CustomerForm()
    if id is None and entity == "bill":
        form = BillForm()
    if id is None and entity == "inventory":
        form = InventoryForm()
    if id is None and entity == "support":
        form = SupportCasesForm()

    if request.method == 'POST':
        form = None
        customer_foreign = None
        if entity == "customer":
            if action.lower() == "create":
                form = CustomerForm(request.POST)
            elif action.lower() == "update":
                customer = Customer.objects.get(id=id)
                form = CustomerForm(request.POST, instance=customer)
        if entity == "bill":
            if action.lower() == "create":
                form = BillForm(request.POST)
                # customer_foreign = Customer.objects.get(id=form.instance.customer.id)
                # print(form.instance.month_bill)
                # customer_foreign.billed_month = form.instance.month_bill
                # customer_foreign.save()
            elif action.lower() == "update":
                bill = Bill.objects.get(bill_id=id)
                form = BillForm(request.POST, instance=bill)

        if entity == "inventory":
            if action.lower() == "create":
                form = InventoryForm(request.POST)
            elif action.lower() == "update":
                inventory = Inventory.objects.get(product_id=id)
                form = InventoryForm(request.POST, instance=inventory)
        if entity == "support":

            if action.lower() == "create":
                form = SupportCasesForm(request.POST)
            elif action.lower() == "update":
                supportCase = SupportCases.objects.get(case_id=id)
                form = SupportCasesForm(request.POST, instance=supportCase)

        if form.is_valid():
            data_object = form.save(commit=False)
            # student.user = request.user  # Set the user object here
            data_object.save()  # Now you can send it to DB
            # template = loader.get_template('index.html')
            #
            # customers = Customer.objects.all()
            # context = {
            #     'customers': customers,
            # }
            # return HttpResponse(template.render(context, request))
            # customer_foreign.save()
            # print(customer_foreign.billed_month)

            if (action.lower() == "update" or "create") and entity == "bill":
                customer_foreign = Customer.objects.get(id=form.instance.customer.id)
                print(customer_foreign)
                customer_foreign.billed_month = form.instance.month_bill
                print(form.instance.month_bill)
                customer_foreign.save()

            return redirect(index)

    context = {'form': form,
               'entity': entity,
               'action': "create" if id is None else "update",
               'id': id
               }
    return render(request, "update.html", context)


class CustomerAutocomplete(View):
    def get(self, request):
        query = request.GET.get('term', '')
        print(query)
        customers = Customer.objects.filter(full_name__icontains=query)[:10]
        results = [str(customer.id) + " " + customer.full_name for customer in customers]
        print(results)
        return JsonResponse(results, safe=False)
