from django.db.models import Sum
from django.shortcuts import render
from django.shortcuts import get_object_or_404, render
from django.http import Http404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views import generic

from collabs.models import *
from collabs.list_pdf_export import render_to_pdf
from datetime import datetime

# Create your views here.


def ExportPdfView(request):
    if not "dtDate__range__gte" in request.GET.keys():
        start = datetime.today().replace(day=1,hour=0, minute=0)
    else:
        start = request.GET['dtDate__range__gte']
    if not "dtDate__range__lte" in request.GET.keys():
        end = datetime.now()
    else:
        end = request.GET['dtDate__range__lte']
    template_name = "pdf_template.html"
    records = Collabs_hour.objects.filter(dtDate__range=[start,end])
    return render_to_pdf(template_name,{"record": records, "start":start, "end":end})


class ExportView(generic.ListView):
    model = Collabs_hour
    template_name = 'collabs_hour/detail.html'
    context_object_name = 'latest_hour_list'



    def get_queryset(self):
        collabs = Collabs_hour.objects.filter(dtCreated__year=self.kwargs.get("year"), dtCreated__month= self.kwargs.get("month"))
        ret = []
        last_user = 0
        for collab in collabs:
            print(f"last_id = {last_user} id={collab.user}")
            if last_user != collab.user:
                last_user = collab.user

            #collab.total = collab.get_total_hour_by_user(self.kwargs.get("year"), self.kwargs.get("month"))
            ret.append(collab)


        return ret
