
from django.shortcuts import render, redirect, get_object_or_404
from .forms import LineInspectionForm, LineInspectionAlcoholicForm, LineInspectionAlcoholicUpdateForm, LineInspectionNonAlcoholicForm, LineInspectionNonAlcoholicUpdateForm, LineInspectionFaultForm, LineInspectiontDefectForm, LineInspectionFaultUpdateForm, LineInspectionSubmitWorkflowForm, LineInspectionCheckWorkflowForm, LineInspectionApprovalWorkflowForm, LineInspectionFilesModelForm
from .models import LineInspectionModel, LineInspectionFaultModel, LineInspectiontDefectModel, LineInspectionWorkFlowModel, LineInspectionFilesModel
from .models_analysis import LineInspectionAlcModel, LineInspectionNonAlcModel
from django.contrib.auth.decorators import login_required
from rest_framework import status
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, renderer_classes, authentication_classes, permission_classes
from django.contrib import messages


""" LINE INSPECTION HOURLY DETAILS =================================================================================================== """
@login_required(login_url='/login')
#@cache_page(60 * 30)
def line_inspection_hourly_detail(request, form_pk, hour_pk):
    template_name = 'hourly/line_inspection_hourly_detail.html'
    #query = get_object_or_404(LineAlcModel, pk=pk)

    if request.GET.get('product_type') == "ALCOHOLIC":
        query = LineInspectionAlcModel.objects.select_related('line_id').filter(pk=hour_pk).first()
        form = LineInspectionAlcoholicUpdateForm(instance=query)
        res_form = LineInspectionAlcoholicUpdateForm(request.POST, instance=query)
    elif request.GET.get('product_type') == "NON-ALCOHOLIC":
        query = LineInspectionNonAlcModel.objects.select_related('line_id').filter(pk=hour_pk).first()
        form = LineInspectionNonAlcoholicUpdateForm(instance=query)
        res_form = LineInspectionNonAlcoholicUpdateForm(request.POST, instance=query)
    else:
        return redirect(f'/line/inspection/detail/{form_pk}/')

    if request.method == 'POST':
        if res_form.is_valid():
            res_form.save()
            messages.success(request, f'{query.hour} Hour Line Inspection Updated')
            return redirect(f'/line/inspection/hour/{form_pk}/{hour_pk}/?product_type={request.GET.get("product_type")}')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/inspection/hour/{form_pk}/{hour_pk}/?product_type={request.GET.get("product_type")}')
    else:
        
        context = {
            'data':query,
            'form':form,
            'product_type': request.POST.get('product_type')
        }
    return render(request, template_name, context)


""" LINE INSPECTION HOURLY DELETE =================================================================================================== """
@login_required(login_url='/login')
def line_inspection_hourly_delete(request, pk):

    if request.method == 'POST':
        product_type = request.POST.get('product_type')
        if product_type == "ALCOHOLIC":
            query = get_object_or_404(LineInspectionAlcModel, pk=pk)
        elif product_type == "NON-ALCOHOLIC":
            query = get_object_or_404(LineInspectionNonAlcModel, pk=pk)
        else:
            return redirect(f'/line/inspection/')

        yes_no = request.POST.get('yes_no')
        if yes_no == 'YES':
            query.delete()
            messages.success(request, 'Line Hourly Inspection Deleted')
            return redirect(f'/line/inspection/detail/{query.line_id.id}/')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/inspection/hour/{query.line_id.id}/{pk}/')
    
    messages.error(request, 'Method not Allowed!!!')
    return redirect(f'/line/inspection/')



""" LINE INSPECTION DEFECT OBSERVED HOURLY =================================================================================================== """
@login_required(login_url='/login')
def create_defect(request, pk):
    #query = get_object_or_404(SachetAlcModel, pk=pk)

    product_type = request.GET.get('product_type')
    if product_type == "ALCOHOLIC":
        query = get_object_or_404(LineInspectionAlcModel, pk=pk)
    elif product_type == "NON-ALCOHOLIC":
        query = get_object_or_404(LineInspectionNonAlcModel, pk=pk)
    else:
        return redirect(f'/line/inspection/')

    if request.method == 'POST':
        form = LineInspectiontDefectForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.line_id = query.line_id
            obj.hour = query.hour
            obj.created_by = request.user.username
            obj.save()
            messages.success(request, 'Line Inspection Defect added successfully')
            return redirect(f'/line/inspection/hour/{query.line_id.id}/{pk}/')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/inspection/hour/{query.line_id.id}/{pk}/')
    messages.error(request, 'Method not Allowed!!!')
    return redirect(f'/line/inspection/hour/{query.line_id.id}/{pk}/')





""" LINE INSPECTION FAULT DETAILS =================================================================================================== """
@login_required(login_url='/login')
#@cache_page(60 * 30)
def line_inspection_fault_detail(request, pk):
    template_name = 'fault/line_inspection_fault_detail.html'
    query = LineInspectionFaultModel.objects.select_related('line_id').filter(pk=pk).first()

    if not query:
        messages.error(request, 'Not Found!!!')
        return redirect(f'/line/inspection/')

    if request.method == 'POST':
        form = LineInspectionFaultUpdateForm(request.POST, instance=query)
        if form.is_valid():
            form.save()
            messages.success(request, f'{query.hour} Hour Fault Updated')
            return redirect(f'/line/inspection/fault/{pk}')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/inspection/fault/{pk}')
    else:
        context = {
            'data':query,
            'form':LineInspectionFaultUpdateForm(instance=query),
        }
    return render(request, template_name, context)


""" LINE INSPECTION FAULT DELETE =================================================================================================== """
@login_required(login_url='/login')
def line_inspection_fault_delete(request, pk):

    if request.method == 'POST':
        yes_no = request.POST.get('yes_no')
        if yes_no == 'YES':
            query = get_object_or_404(LineInspectionFaultModel, pk=pk)       
            query.delete()
            messages.success(request, 'Line Inspection Fault Deleted')
            return redirect(f'/line/inspection/detail/{query.line_id.id}/')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/inspection/fault/{pk}/')
    messages.error(request, 'Method not Allowed!!!')
    return redirect(f'/line/inspection/fault/{pk}/')


