
from django.shortcuts import render, redirect, get_object_or_404
#from .models import LineAnalysisModel, LineFaultModel, LineWorkFlowModel
from .models_analysis import LineAlcModel, LineNonAlcModel
from .forms import LineAlcoholicAnalysisForm, LineNonAlcoholicAnalysisForm, LineFaultUpdateForm, LineAlcoholicAnalysisUpdateForm, LineNonAlcoholicAnalysisUpdateForm
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 ANALYSIS HOURLY DETAILS =================================================================================================== """
@login_required(login_url='/login')
#@cache_page(60 * 30)
def line_analysis_hourly_detail(request, form_pk, hour_pk):
    template_name = 'hourly/line_analysis_hourly_detail.html'
    #query = get_object_or_404(LineAlcModel, pk=pk)

    if request.GET.get('product_type') == "ALCOHOLIC":
        query = LineAlcModel.objects.select_related('line_id').filter(pk=hour_pk).first()
        form = LineAlcoholicAnalysisUpdateForm(instance=query)
        res_form = LineAlcoholicAnalysisUpdateForm(request.POST, instance=query)
    elif request.GET.get('product_type') == "NON-ALCOHOLIC":
        query = LineNonAlcModel.objects.select_related('line_id').filter(pk=hour_pk).first()
        form = LineNonAlcoholicAnalysisUpdateForm(instance=query)
        res_form = LineNonAlcoholicAnalysisUpdateForm(request.POST, instance=query)
    else:
        return redirect(f'/line/analysis/detail/{form_pk}/')

    if request.method == 'POST':
        if res_form.is_valid():
            res_form.save()
            messages.success(request, f'{query.hour} Hour Line Analysis Updated')
            return redirect(f'/line/analysis/hour/{form_pk}/{hour_pk}/?product_type={request.GET.get("product_type")}')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/analysis/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 ANALYSIS HOYRLY DELETE =================================================================================================== """
@login_required(login_url='/login')
def line_analysis_hourly_delete(request, pk):

    if request.method == 'POST':
        product_type = request.POST.get('product_type')
        if product_type == "ALCOHOLIC":
            query = get_object_or_404(LineAlcModel, pk=pk)
        elif product_type == "NON-ALCOHOLIC":
            query = get_object_or_404(LineNonAlcModel, pk=pk)
        else:
            return redirect(f'/line/analysis/')
        yes_no = request.POST.get('yes_no')
        if yes_no == 'YES':
            query.delete()
            messages.success(request, 'Line Hourly Analysis Deleted')
            return redirect(f'/line/analysis/detail/{query.line_id.id}/')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/analysis/hour/{query.line_id.id}/{pk}/')




from .models import LineFaultModel
""" LINE ANALYSIS FAULT DETAILS =================================================================================================== """
@login_required(login_url='/login')
#@cache_page(60 * 30)
def line_analysis_fault_detail(request, pk):
    template_name = 'fault/line_analysis_fault_detail.html'
    query = LineFaultModel.objects.select_related('line_id').filter(pk=pk).first()

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


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

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



"""
 ALCOHOLIC LINES ANALYSIS MODEL 
@api_view(('GET','POST', 'PUT', 'DELETE'))
@permission_classes([IsAuthenticated])
def line_alcoholic_api(request, pk=0):
    if request.method == 'GET':
        if pk == 0:
            if request.GET.get('line_id'):
                query = LineAlcModel.objects.filter(line_id__id=request.GET.get('line_id'))
            else:
                query = LineAlcModel.objects.all()
        else:
            query = LineAlcModel.objects.filter(pk=pk)
            if query.count() == 0:
                return Response({"error":"Not Found"}, status=status.HTTP_404_NOT_FOUND)

        serializer_class = LineAlcSerializer(query, many=True)
        return Response({"data":serializer_class.data}, status=status.HTTP_200_OK)

    elif request.method == 'POST':
        res_data = JSONParser().parse(request)
        check_query = LineAlcModel.objects.filter(line_id__id=res_data['line_id']).filter(hour=res_data['hour'])
        if check_query.first():
            serializer_obj = LineAlcSerializer(check_query, many=True)
            return Response({"error":"Already Exist", "data":serializer_obj.data}, status=status.HTTP_409_CONFLICT)

        serializer_obj = LineAlcSerializer(data=res_data)
        if serializer_obj.is_valid(raise_exception=True):
            serializer_obj.save()
            return Response({"data":serializer_obj.data}, status=status.HTTP_201_CREATED)
        return Response({"error":serializer_obj.errors}, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        query = LineAlcModel.objects.filter(pk=data['id']).first()
        
        if not query:
            return Response({"error":"Not Found"}, status=status.HTTP_404_NOT_FOUND)
        
        if request.user.profile.role != 'SUPERADMIN':
            if request.user.username != query.created_by:
                return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)

        serializer_obj = LineAlcSerializer(query, data=data)
        if serializer_obj.is_valid(raise_exception=True):
            serializer_obj.save()
            return Response({"data":serializer_obj.data}, status=status.HTTP_200_OK)
        return Response({"error":serializer_obj.errors}, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        
        if request.user.profile.role != 'SUPERADMIN':
            return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)

        query = LineAlcModel.objects.select_related('line_id').filter(pk=pk).first()
        if not query:
            return Response({"error":"Not Found"}, status=status.HTTP_404_NOT_FOUND)

        if query.line_id.status == 'APPROVED':
            return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)

        if query.line_id.status == 'CHECKED' and query.line_id.workflow.checked_by != request.user.username:
                return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)
        
        query.delete()
        return JsonResponse("Deleted Successfully", safe=False)




NON ALCOHOLIC LINES ANALYSIS MODEL
@api_view(('GET','POST', 'PUT', 'DELETE'))
@permission_classes([IsAuthenticated])
def line_non_alcoholic_api(request, pk=0):
    if request.method == 'GET':
        if pk == 0:
            if request.GET.get('line_id'):
                query = LineNonAlcModel.objects.filter(line_id__id=request.GET.get('line_id'))
            else:
                query = LineNonAlcModel.objects.all()
        else:
            query = LineNonAlcModel.objects.filter(pk=pk)
            if query.count() == 0:
                return Response({"error":"Not Found"}, status=status.HTTP_404_NOT_FOUND)

        serializer_class = LineNonAlcSerializer(query, many=True)
        return Response({"data":serializer_class.data}, status=status.HTTP_200_OK)

    elif request.method == 'POST':
        res_data = JSONParser().parse(request)
        check_query = LineNonAlcModel.objects.filter(line_id__id=res_data['line_id']).filter(hour=res_data['hour'])
        if check_query.first():
            serializer_obj = LineNonAlcSerializer(check_query, many=True)
            return Response({"error":"Already Exist", "data":serializer_obj.data}, status=status.HTTP_409_CONFLICT)

        serializer_obj = LineNonAlcSerializer(data=res_data)
        if serializer_obj.is_valid(raise_exception=True):
            serializer_obj.save()
            return Response({"data":serializer_obj.data}, status=status.HTTP_201_CREATED)
        return Response({"error":serializer_obj.errors}, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        query = LineNonAlcModel.objects.filter(pk=data['id']).first()
        
        if not query:
            return Response({"error":"Not Found"}, status=status.HTTP_404_NOT_FOUND)


        if request.user.profile.role != 'SUPERADMIN':
            if request.user.username != query.created_by:
                return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)


        if query.line_id.status == 'APPROVED':
            return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)

        if query.line_id.status == 'CHECKED':
            if query.line_id.workflow.checked_by != request.user.username or request.user.profile.role != 'SUPERADMIN':
                return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)

        serializer_obj = LineNonAlcSerializer(query, data=data)
        if serializer_obj.is_valid(raise_exception=True):
            serializer_obj.save()
            return Response({"data":serializer_obj.data}, status=status.HTTP_200_OK)
        return Response({"error":serializer_obj.errors}, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        
        if request.user.profile.role != 'SUPERADMIN':
            return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)

        query = LineNonAlcModel.objects.select_related('line_id').filter(pk=pk).first()
        if not query:
            return Response({"error":"Not Found"}, status=status.HTTP_404_NOT_FOUND)

        if query.line_id.status == 'APPROVED':
            return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)

        if query.line_id.status == 'CHECKED' and query.line_id.workflow.checked_by != request.user.username:
                return Response({"error":"Not Allowed"}, status=status.HTTP_401_UNAUTHORIZED)
        
        query.delete()
        return JsonResponse("Deleted Successfully", safe=False)


"""