from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from accounts.models import UserProfile

from django.utils import timezone
from datetime import datetime, date
from django.db.models import F, Sum, Avg
from django.db.models import Q

from itertools import chain
from datetime import datetime, date, timedelta
from django.http.response import JsonResponse
from accounts.models import UsersActivitiesModel

from line_analysis.models import LineAnalysisModel
from line_inspection.models import LineInspectionModel
from sachet_analysis.models import SachetAnalysisModel
from sachet_inspection.models import SachetInspectionModel

from utilz.fxns import paginate


""" HOME =================================================================================================== """
@login_required(login_url='/login')
def home(request):
    template_name = 'home.html'
    day_from_date = datetime.today() - timedelta(days=7)
    month_from_date = datetime.today() - timedelta(days=30)
    #month3_from_date = datetime.today() - timedelta(days=90)
    #year_from_date = datetime.today() - timedelta(days=365)
    curr_date = datetime.today()

    day_la = LineAnalysisModel.objects.filter(date__range=[day_from_date, curr_date]).count()
    month_la = LineAnalysisModel.objects.filter(date__range=[month_from_date, curr_date]).count()

    day_li = LineInspectionModel.objects.filter(date__range=[day_from_date, curr_date]).count()
    month_li = LineInspectionModel.objects.filter(date__range=[month_from_date, curr_date]).count()

    day_sa = SachetAnalysisModel.objects.filter(date__range=[day_from_date, curr_date]).count()
    month_sa = SachetAnalysisModel.objects.filter(date__range=[month_from_date, curr_date]).count()

    day_si = SachetInspectionModel.objects.filter(date__range=[day_from_date, curr_date]).count()
    month_si = SachetInspectionModel.objects.filter(date__range=[month_from_date, curr_date]).count()

    line_analysis = [{'description':f'Line {l["line"]} Aanalysis Form', 'shift':l['shift'], 'link':f'/line/analysis/detail/{l["id"]}', 'form':'Line Analysis', 'product':f'{l["product"]}/{l["product_size"]}', 'datetime_created':l['datetime_created']} for l in list(LineAnalysisModel.objects.all().values())]
    line_inspection = [{'description':f'Line {l.l_id.line} Inspection Form', 'shift':l.shift, 'link':f'/line/inspection/detail/{l.id}', 'form':'Line Inspection', 'product':f'{l.product_id.product_name}/{l.product_id.product_size}', 'datetime_created':l.datetime_created} for l in LineInspectionModel.objects.all().order_by('shift', 'l_id')]
    sachet_analysis = [{'description':f'Machine {l.mc_id.machine} Aanalysis Form', 'shift':l.shift, 'link':f'/sachet/analysis/detail/{l.id}', 'form':'Sachet Analysis', 'product':f'{l.product_id.product_name}/{l.product_id.product_size}', 'datetime_created':l.datetime_created} for l in SachetAnalysisModel.objects.all().order_by('shift', 'mc_id')]
    sachet_inspection = [{'description':f'Machine {l.mc_id.machine} Aanalysis Form', 'shift':l.shift, 'link':f'/sachet/inspection/detail/{l.id}', 'form':'Sachet Inspection', 'product':f'{l.product_id.product_name}/{l.product_id.product_size}', 'datetime_created':l.datetime_created } for l in SachetInspectionModel.objects.all().order_by('shift', 'mc_id')]
    
    data = sorted(chain(line_analysis, line_inspection, sachet_analysis, sachet_inspection), key=lambda x: x['datetime_created'], reverse=True)[:200]

    context = {
        'day_la':day_la,
        'month_la':month_la,
        'day_li':day_li,
        'month_li':month_li,
        'day_sa':day_sa,
        'month_sa':month_sa,
        'day_si':day_si,
        'month_si':month_si,
        'data': paginate(request, query=data, page_number=60)
    }
    return render(request, template_name, context)



""" LAYOUT DATE SEARCH =================================================================================================== """
@login_required(login_url='/login')
def layout_date_search(request):
    template_name = 'layout_date_search.html'

    if request.method== 'POST':
        layout_date_search = request.POST.get('layout_date_search')
        line_analysis = [{'description':f'Line {l["line"]} Aanalysis Form', 'shift':l['shift'], 'link':f'/line/analysis/detail/{l["id"]}', 'form':'Line Analysis', 'product':f'{l["product"]}/{l["product_size"]}'} for l in list(LineAnalysisModel.objects.filter(date=layout_date_search).order_by('shift', 'line').values())]
        line_inspection = [{'description':f'Line {l.l_id.line} Inspection Form', 'shift':l.shift, 'link':f'/line/inspection/detail/{l.id}', 'form':'Line Inspection', 'product':f'{l.product_id.product_name}/{l.product_id.product_size}'} for l in LineInspectionModel.objects.filter(date=layout_date_search).order_by('shift', 'l_id')]
        sachet_analysis = [{'description':f'Machine {l.mc_id.machine} Aanalysis Form', 'shift':l.shift, 'link':f'/sachet/analysis/detail/{l.id}', 'form':'Sachet Analysis', 'product':f'{l.product_id.product_name}/{l.product_id.product_size}'} for l in SachetAnalysisModel.objects.filter(date=layout_date_search).order_by('shift', 'mc_id')]
        sachet_inspection = [{'description':f'Machine {l.mc_id.machine} Aanalysis Form', 'shift':l.shift, 'link':f'/sachet/inspection/detail/{l.id}', 'form':'Sachet Inspection', 'product':f'{l.product_id.product_name}/{l.product_id.product_size}'} for l in SachetInspectionModel.objects.filter(date=layout_date_search).order_by('shift', 'mc_id')]
        
        data = line_analysis + line_inspection + sachet_analysis + sachet_inspection
        context = {
            'data':data,
            'date_search':layout_date_search
        }
        return render(request, template_name, context)
    else:
        messages.error(request, 'Method not allowed!!!')
        return redirect('/')
