from django.shortcuts import render, redirect, get_object_or_404
from .forms import SachetInspectionForm, SachetInspectionUpdateForm, SachetInspectionPkgCodeForm, SachetInspectionFaultForm, SachetInspectionDespatchPalletForm, SachetInspectionAlcForm, SachetInspectionSubmitWorkflowForm, SachetInspectionCheckWorkflowForm, SachetInspectionApprovalWorkflowForm, SachetInspectionFilesForm 
from .models import SachetInspectionModel, SachetInspectionDefectModel, SachetInspectionWorkFlowModel, SachetInspectionFilesModel, SachetInspectionPkgCodeModel
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.decorators.cache import cache_page
from utilz.fxns import set_sachet_shift_inspection_table, actions_validator, paginate
from accounts.fxns import user_activity
from dispute.models import DisputeModel
from dispute.forms import DisputeCreateForm



""" SACHET INSPECTION =================================================================================================== """
@login_required(login_url='/login')
def sachet_inspection(request):
    template_name = 'sachet_inspection.html'
    

    if request.method == 'POST':
        checker = SachetInspectionModel.objects.filter(date=request.POST.get('date')).filter(shift=request.POST.get('shift')).filter(mc_id=request.POST.get('mc_id')).first()
        
        if checker:
            messages.error(request, 'Form already exists')
            return redirect(f'/sachet/inspection/detail/{checker.id}/')
        form = SachetInspectionForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.created_by = request.user.username
            obj.save()

            SachetInspectionWorkFlowModel(machine_id=obj).save()

            """ USER ACTIVITY """
            user_activity(request, model_name='SACHET_INSPECTION', model_id=obj.id, activity='CREATE', description=f"Sachet {obj.mc_id.machine} Inspection form Created")

            messages.success(request, 'Sachet Inspection Form Created')
            return redirect(f'/sachet/inspection/detail/{obj.id}/')
        messages.error(request, 'Error in Connection!!!')
        return redirect('/sachet/inspection/')
    else:
        query = SachetInspectionModel.objects.all().order_by('-date')
        context = {
            'data': paginate(request, query=query, page_number=60),
            'form':SachetInspectionForm(),
        }
    return render(request, template_name, context)


""" SACHET INSPECTION DETAILS =================================================================================================== """
@login_required(login_url='/login')
#@cache_page(60 * 30)
def sachet_inspection_detail(request, pk):
    template_name = 'sachet_inspection_detail.html'
    query = get_object_or_404(SachetInspectionModel, pk=pk)

    

    if request.method == 'POST':
        form = SachetInspectionUpdateForm(request.POST, instance=query)
        if form.is_valid():
            form.save()

            """ USER ACTIVITY """
            user_activity(request, model_name='SACHET_INSPECTION', model_id=query.id, activity='UPDATE', description=f"Sachet {query.mc_id.machine} Inspection form Updated")

            messages.success(request, 'Sachet Inspection Form Updated')
            return redirect(f'/sachet/inspection/detail/{pk}/')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/sachet/inspection/detail/{pk}/')
    else:
        
        analysis_data = list(query.hourly.all().values())

        fault_data = list(query.fault.all().values())

        defect_data = query.defect.all()
        
        shift_data = set_sachet_shift_inspection_table(shift=query.shift, analysis_data=analysis_data, fault_data=fault_data, defect_data=defect_data)#, product_type=product_type)

        workflow = query.workflow

        if len(shift_data[0]) > 0:
            actions =  actions_validator(request, status=query.status, workflow={'analysed_by':workflow.analysed_by, 'checked_by':workflow.checked_by}, has_dependency=True)
        else:
            actions =  actions_validator(request, status=query.status, workflow={'analysed_by':workflow.analysed_by, 'checked_by':workflow.checked_by}, has_dependency=False)

        #print('query_files====================================',dir(query.files))
        context = {
            'data':query,
            'analysis_data':shift_data[0],
            'available_hours':',,'.join(shift_data[1]),
            'defect': defect_data,
            'workflow': workflow,
            'pkg_codes': query.pkg_code.all(),
            'pallet': query.sachet_pallet.all(),
            'form': SachetInspectionUpdateForm(instance=query),
            'fault_form': SachetInspectionFaultForm(),
            'analysis_form': SachetInspectionAlcForm(),
            'submit_form':SachetInspectionSubmitWorkflowForm(instance=workflow),
            'check_form': SachetInspectionCheckWorkflowForm(instance=workflow),
            'approve_form': SachetInspectionApprovalWorkflowForm(instance=workflow),
            'upload_form': SachetInspectionFilesForm(),
            'pkg_form' : SachetInspectionPkgCodeForm(),
            'despatch_form': SachetInspectionDespatchPalletForm(),
            'dispute_form':DisputeCreateForm(),
            'files': list(SachetInspectionFilesModel.objects.filter(machine_id=query).values()),#.files if hasattr(query, 'files') else None,
            'actions': actions,
            'disputes': list(DisputeModel.objects.filter(model_name='SACHET_INSPECTION', model_id=pk).values())
        }
    return render(request, template_name, context)



""" SACHET ANALYSIS DELETE =================================================================================================== """
@login_required(login_url='/login')
def sachet_inspection_delete(request, pk):
    query = get_object_or_404(SachetInspectionModel, pk=pk)

    if request.method == 'POST':
        yes_no = request.POST.get('yes_no')
        if yes_no == 'YES':
            query.delete()
            messages.success(request, 'Sachet Inspection Form Deleted')
            return redirect('/sachet/inspection/')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/sachet/inspection/detail/{pk}/')



""" CREATE SACHET INSPECTION HOURLY =================================================================================================== """
@login_required(login_url='/login')
def sachet_inspection_hourly(request, pk):
    query = get_object_or_404(SachetInspectionModel, pk=pk)

    if request.method == 'POST':
        analysis_form = SachetInspectionAlcForm(request.POST)
        check = query.hourly.filter(hour=request.POST.get('hour')).first()
        if check:
            messages.error(request, 'Hour already inspection')
            return redirect(f'/sachet/inspection/hour/{check.id}/')

        if analysis_form.is_valid():
            obj =analysis_form.save(commit=False)
            obj.machine_id = query
            obj.created_by = request.user.username
            obj.save()
            messages.success(request, f'Sachet Inspection for {request.POST.get("hour")} Hour Created')
            return redirect(f'/sachet/inspection/hour/{pk}/{obj.id}/')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/sachet/inspection/detail/{pk}/')



""" CREATE SACHET INSPECTION FAULT =================================================================================================== """
@login_required(login_url='/login')
def sachet_inspection_create_fault(request, pk):
    query = get_object_or_404(SachetInspectionModel, pk=pk)

    if request.method == 'POST':
        form = SachetInspectionFaultForm(request.POST)

        if form.is_valid():
            obj =form.save(commit=False)
            obj.machine_id = query
            obj.created_by = request.user.username
            obj.save()
            messages.success(request, f'Sachet Fault for {request.POST.get("hour")} Hour Created')
            return redirect(f'/sachet/inspection/fault/{obj.id}')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/sachet/inspection/detail/{pk}/')

    messages.error(request, 'Method not allowed!!!')
    return redirect(f'/sachet/inspection/detail/{pk}/')



""" SACHET INSPECTION FORM PRINT OUT =============================================== """
from utilz.fxns import form_set_shift_analysis_table
from utilz.models import SHIFTS
DEFECT_CAUSE = {"RAW MATERIAL":"M", "ENGINEERING":"E", "MAINTENANCE SETTING":"W", "HUMAN":"O"}
DEFECT_CATEGORY = {"MINOR" : "x", "MAJOR" : "Y", "CRITICAL" : "Z"}
@login_required(login_url='/login')
def sachet_inspection_form(request, pk):
    query = get_object_or_404(SachetInspectionModel, pk=pk)
    template_name = 'sachet_inspection_form.html'

    analysis_data = query.hourly.all().order_by('hour')

    fault_data = query.fault.all().order_by('hour')
    
    form_data = form_set_shift_analysis_table(shift=query.shift, analysis_data=analysis_data, fault_data=fault_data)

    workflow = query.workflow

    defect_data = query.defect.all().order_by('hour')

    for k,v in form_data.items():
        form_data[k]['defect'] = ', '.join([f'{DEFECT_CATEGORY[d.defect_id.defect_category]}{d.quantity}:{d.defect_id.defect_code}:{DEFECT_CAUSE[d.defect_cause]}' for d in defect_data.filter(hour=k)])
    
    pkg_s = list(query.pkg_code.all().values())
    pkg_code = {}
    pkg_code['film_code'] = ', '.join(list(dict.fromkeys([p['pkg_code'] for p in pkg_s if p['material_type'] == 'FILM_CODE' ])))
    pkg_code['case_code'] = ', '.join(list(dict.fromkeys([p['pkg_code'] for p in pkg_s if p['material_type'] == 'CASE_CODE' ])))
    pkg_code['minipack_code'] = ', '.join(list(dict.fromkeys([p['pkg_code'] for p in pkg_s if p['material_type'] == 'MINIPACK_CODE' ])))
    pkg_code['pouch_code'] = ', '.join(list(dict.fromkeys([p['pkg_code'] for p in pkg_s if p['material_type'] == 'POUCH_CODE' ])))

    context = {
        'data':query,
        'form_data':form_data,
        'workflow': workflow,
        'hours':SHIFTS[query.shift],
        'fault_data':fault_data,
        'defect_data':defect_data,
        'pkg_code': pkg_code
    }
    return render(request, template_name, context)



""" FILE UPLOAD MODEL ========================================== """
@login_required(login_url='/login')
def file_upload(request, pk):
    query = get_object_or_404(SachetInspectionModel, pk=pk)

    if request.method == "POST":
        form = SachetInspectionFilesForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.machine_id = query
            obj.created_by = request.user.username
            obj.save()
            messages.success(request, f"File Uploaded")
            return redirect(f'/sachet/inspection/detail/{pk}/')
        else:
            messages.error(request, f"File Upload Failed!!!")
            return redirect(f'/sachet/inspection/detail/{pk}/')
    else:
        messages.error(request, f"Method not Allowed!!!")
        return redirect(f'/sachet/inspection/detail/{pk}/')


""" FILE DELETE MODEL ========================================== """
@login_required(login_url='/login')
def file_delete(request, pk):
    query = get_object_or_404(SachetInspectionFilesModel, pk=pk)
    if query.created_by == request.user.username:
        query.delete()
        messages.success(request, f"File Deleted successfully")
    else:
        messages.error(request, 'Action not allowed!!!')
    return redirect(f'/sachet/inspection/detail/{query.machine_id.id}/')



""" DEFECT DELETE MODEL ========================================== """
@login_required(login_url='/login')
def defect_delete(request, pk):
    query = get_object_or_404(SachetInspectionDefectModel, pk=pk)
    analysis_pk = request.GET.get('analysis')
    if query.created_by == request.user.username:
        query.delete()
        messages.success(request, f"Defect Deleted successfully")
    else:
        messages.error(request, 'Action not allowed!!!')
    return redirect(f'/sachet/inspection/hour/{query.machine_id.id}/{analysis_pk}')




""" ADD PKG CODE MODEL ========================================== """
@login_required(login_url='/login')
def pkg_code_add(request, pk):
    query = get_object_or_404(SachetInspectionModel, pk=pk)

    if request.method == "POST":
        form = SachetInspectionPkgCodeForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.machine_id = query
            obj.created_by = request.user.username
            obj.save()
            messages.success(request, f"Pkg Code Added")
            return redirect(f'/sachet/inspection/detail/{pk}/')
        else:
            messages.error(request, f"Network Error!!!")
            return redirect(f'/sachet/inspection/detail/{pk}/')
    else:
        messages.error(request, f"Method not Allowed!!!")
        return redirect(f'/sachet/inspection/detail/{pk}/')


""" DELETE PKG CODE MODEL ========================================== """
@login_required(login_url='/login')
def pkg_code_delete(request, pk):
    query = get_object_or_404(SachetInspectionPkgCodeModel, pk=pk)
    if query.created_by == request.user.username:
        query.delete()
        messages.success(request, f"Defect Deleted successfully")
    else:
        messages.error(request, 'Action not allowed!!!')
    return redirect(f'/sachet/inspection/detail/{query.machine_id.id}/')





""" ADD DESPATCHED PALLET """
@login_required(login_url='/login')
def pallet_add(request, pk):
    query = get_object_or_404(SachetInspectionModel, pk=pk)

    if request.method == "POST":
        form = SachetInspectionDespatchPalletForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.machine_id = query
            obj.created_by = request.user.username
            obj.save()
            messages.success(request, f"Pallet Added")
            return redirect(f'/sachet/inspection/detail/{pk}/')
        else:
            messages.error(request, f"Failed!!!")
            return redirect(f'/sachet/inspection/detail/{pk}/')
    else:
        messages.error(request, f"Method not Allowed!!!")
        return redirect(f'/sachet/inspection/detail/{pk}/')



""" DELETE DESPATCHED PALLET ========================================== """
from .models import SachetInspectionDespatchPalletModel
@login_required(login_url='/login')
def pallet_delete(request, pk):
    query = get_object_or_404(SachetInspectionDespatchPalletModel, pk=pk)

    if query.created_by == request.user.username:
        query.delete()
        messages.success(request, f"Pallet Deleted successfully")
    else:
        messages.error(request, 'Action not allowed!!!')
    return redirect(f'/sachet/inspection/detail/{query.machine_id.id}/')