from django.http.response import JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import LineAnalysisModel, LineFaultModel, LineAnalysisWorkFlowModel
from .models_analysis import LineAlcModel, LineNonAlcModel
from .forms import LineAnalysisForm, LineFaultForm, LineAlcoholicAnalysisForm, LineNonAlcoholicAnalysisForm, LineAnalysisWorkflowForm, LineCheckWorkflowForm, LineApprovalWorkflowForm, LineAnalysisFilesModelForm
from utilz.models import ProductsModel, LinesModel
from django.views.decorators.cache import cache_page
from utilz.fxns import set_case_code, set_shift_analysis_table, actions_validator, paginate
from accounts.fxns import user_activity
from dispute.models import DisputeModel
from dispute.forms import DisputeCreateForm


""" LINE ANALYSIS =================================================================================================== """
@login_required(login_url='/login')
def line_analysis(request):
    template_name = 'line_analysis.html'
    

    if request.method == 'POST':
        checker = LineAnalysisModel.objects.filter(date=request.POST.get('date'), shift=request.POST.get('shift'), line=request.POST.get('line')).first()

        if checker:
            messages.error(request, 'Form already exists')
            return redirect(f'/line/analysis/detail/{checker.id}/')

        if not ProductsModel.objects.filter(product_name=request.POST.get('product'), product_size=request.POST.get('product_size')).first():
            messages.error(request, 'Product does not exists!!!')
            return redirect(f'/line/analysis/')
        
        form = LineAnalysisForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.created_by = request.user.username
            obj.save()

            LineAnalysisWorkFlowModel(line_id=obj).save()
            user_activity(request, model_name='LINE_ANALYSIS', model_id=obj.id, activity='CREATE', description=f"Line {obj.line} Analysis form Created")

            messages.success(request, 'Line Analysis Form Created')
            return redirect(f'/line/analysis/detail/{obj.id}/')
        messages.error(request, 'Error in Connection!!!')
        return redirect('/line/analysis/')
    else:
        query = LineAnalysisModel.objects.all().order_by('-date')
        products = list(ProductsModel.objects.filter(product_section='LINE').values('product_name', 'product_size'))
        prods = ',,'.join( list(dict.fromkeys([p['product_name'] for p in products])))
        size = ',,'.join( list(dict.fromkeys([str(p['product_size']) for p in products])))
        lines = ',,'.join([str(l['line']) for l in LinesModel.objects.all().values('line')])
        context = {
            'data': paginate(request, query=query, page_number=60),
            'form':LineAnalysisForm(),
            'prods':prods,
            'size':size,
            'lines':lines
        }
    return render(request, template_name, context)


""" LINE ANALYSIS DETAILS =================================================================================================== """
@login_required(login_url='/login')
#@cache_page(60 * 30)
def line_analysis_detail(request, pk):
    template_name = 'line_analysis_detail.html'
    query = get_object_or_404(LineAnalysisModel, pk=pk)

    if query.get_product_type() == "ALCOHOLIC":
        analysis_form = LineAlcoholicAnalysisForm()
        product_type = "ALCOHOLIC"
    elif query.get_product_type() == "NON-ALCOHOLIC":
        analysis_form = LineNonAlcoholicAnalysisForm()
        product_type = "NON-ALCOHOLIC"
    else:
        analysis_form = None

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

            """ USER ACTIVITY """
            user_activity(request, model_name='LINE_ANALYSIS', model_id=query.id, activity='UPDATE', description=f"Line {query.line} Analysis form Updated")

            messages.success(request, 'Line Analysis Form Updated')
            return redirect(f'/line/analysis/detail/{pk}/')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/analysis/detail/{pk}/')
    else:
        
        if product_type == "ALCOHOLIC":
            analysis_data = list(query.hourly.all().values())
        elif product_type == "NON-ALCOHOLIC":
            analysis_data = list(query.hourly1.all().values())

        fault_data = list(query.fault.all().values())
        
        shift_data = set_shift_analysis_table(shift=query.shift, analysis_data=analysis_data, fault_data=fault_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]),
            'workflow': workflow,
            'form':LineAnalysisForm(instance=query),
            'fault_form':LineFaultForm(),
            'analysis_form':analysis_form,
            'product_type':product_type,
            'submit_form':LineAnalysisWorkflowForm(instance=workflow),
            'check_form': LineCheckWorkflowForm(instance=workflow),
            'approve_form': LineApprovalWorkflowForm(instance=workflow),
            'upload_form':LineAnalysisFilesModelForm(),
            'dispute_form':DisputeCreateForm(),
            'files': list(LineAnalysisFilesModel.objects.filter(line_id=query).values()),#.files if hasattr(query, 'files') else None,
            'actions': actions,
            'disputes':list(DisputeModel.objects.filter(model_name='LINE_ANALYSIS', model_id=pk).values())
        }
    return render(request, template_name, context)



""" LINE ANALYSIS DELETE =================================================================================================== """
@login_required(login_url='/login')
def line_analysis_delete(request, pk):
    query = get_object_or_404(LineAnalysisModel, pk=pk)

    if request.method == 'POST':
        yes_no = request.POST.get('yes_no')
        if yes_no == 'YES':
            query.delete()

            """ USER ACTIVITY """
            user_activity(request, model_name='LINE_ANALYSIS', model_id=query.id, activity='DELETE', description=f"Line {query.line} Analysis form Deleted")

            messages.success(request, 'Line Analysis Form Deleted')
            return redirect('/line/analysis/')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/analysis/detail/{pk}/')



""" CREATE LINE ANALYSIS HOURLY =================================================================================================== """
@login_required(login_url='/login')
def line_analysis_hourly(request, pk):
    query = get_object_or_404(LineAnalysisModel, pk=pk)

    if request.method == 'POST':
        if request.POST.get('product_type') == "ALCOHOLIC":
            check = query.hourly.filter(hour=request.POST.get('hour')).first()
            if check:
                return redirect(f'/line/analysis/hour/{check.id}/?product_type=ALCOHOLIC')
            analysis_form = LineAlcoholicAnalysisForm(request.POST)
        elif request.POST.get('product_type') == "NON-ALCOHOLIC":
            check = query.hourly1.filter(hour=request.POST.get('hour')).first()
            if check:
                return redirect(f'/line/analysis/hour/{check.id}/?product_type=NON-ALCOHOLIC')
            analysis_form = LineNonAlcoholicAnalysisForm(request.POST)
        else:
            analysis_form = None

        if analysis_form.is_valid():
            obj =analysis_form.save(commit=False)
            obj.line_id = query
            obj.created_by = request.user.username
            obj.save()
            messages.success(request, f'Line Analysis for {request.POST.get("hour")} Hour Created')
            return redirect(f'/line/analysis/hour/{pk}/{obj.id}/?product_type={request.POST.get("product_type")}')
        messages.error(request, 'Error in Connection!!!')
        return redirect(f'/line/analysis/detail/{pk}/')



""" CREATE LINE ANALYSIS FAULT =================================================================================================== """
@login_required(login_url='/login')
def line_analysis_create_fault(request, pk):
    query = get_object_or_404(LineAnalysisModel, pk=pk)

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

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

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



""" LINE ANALYSIS FORM =============================================== """
from utilz.fxns import form_set_shift_analysis_table
from utilz.models import SHIFTS
@login_required(login_url='/login')
def line_analysis_form(request, pk):
    query = get_object_or_404(LineAnalysisModel, pk=pk)
    template_name = 'form.html'

    product_type = query.get_product_type()

    if product_type == "ALCOHOLIC":
        analysis_data = query.hourly.all().order_by('hour')
    elif product_type == "NON-ALCOHOLIC":
        analysis_data = query.hourly1.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
    
    context = {
        'data':query,
        'form_data':form_data,
        'workflow': workflow,
        'hours':SHIFTS[query.shift],
        'fault_data':fault_data,
        'product_type':product_type
    }
    return render(request, template_name, context)



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

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


""" FILE DELETE MODEL ========================================== """
from .models import LineAnalysisFilesModel
@login_required(login_url='/login')
def file_delete(request, pk):
    query = get_object_or_404(LineAnalysisFilesModel, pk=pk)

    query.delete()

    messages.success(request, f"File Deleted successfully")
    return redirect(f'/line/analysis/detail/{query.line_id.id}/')


