from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.models import User
from datetime import datetime
from django.utils import timezone
from .models import DisputeModel
from .forms import DisputeCreateForm, DisputeCloseForm

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 itertools import chain
from utilz.fxns import paginate

MODEL_CHOICES = ['LINE_ANALYSIS', 'SACHET_ANALYSIS', 'LINE_INSPECTION', 'SACHET_INSPECTION']


""" GET ALL DISPUTES / CREATE DISPUTE """
@login_required(login_url='/login')
def dispute_log(request):
    template_name = 'dispute_log.html'
    query = list(DisputeModel.objects.filter(status='OPEN').order_by('-id').values())   

    if request.method == 'POST':
        model_name = request.POST.get('model_name')
        model_id = request.POST.get('model_id')

        if model_name == 'LINE_ANALYSIS':
            model_obj = get_object_or_404(LineAnalysisModel, pk=model_id)
            success_mssg = f'Dispute raised on Line Analysis Form DATE : {model_obj.date}, LINE : {model_obj.line}'
            redirect_url = f'/line/analysis/detail/{model_id}/'
        elif model_name == 'SACHET_ANALYSIS':
            model_obj = get_object_or_404(SachetAnalysisModel, pk=model_id)
            success_mssg = f'Dispute raised on Sachet Analysis Form DATE : {model_obj.date}, MACHINE : {model_obj.mc_id.machine}'
            redirect_url = f'/sachet/analysis/detail/{model_id}/'
        elif model_name == 'LINE_INSPECTION':
            model_obj = get_object_or_404(LineInspectionModel, pk=model_id)
            success_mssg = f'Dispute raised on Line Inspection Form DATE : {model_obj.date}, MACHINE : {model_obj.l_id.line}'
            redirect_url = f'/line/inspection/detail/{model_id}/'
        elif model_name == 'SACHET_INSPECTION':
            model_obj = get_object_or_404(SachetInspectionModel, pk=model_id)
            success_mssg = f'Dispute raised on Sachet Inspection Form DATE : {model_obj.date}, MACHINE : {model_obj.mc_id.machine}'
            redirect_url = f'/sachet/inspection/detail/{model_id}/'
        else:
            model_obj = None

        if not model_obj or model_obj == None:
            messages.error(request, f"Record not Found!!!")
            return redirect('/dispute/')


        form = DisputeCreateForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.model_name=model_name
            obj.model_id=model_id
            """ SET USER """
            obj.created_by = request.user.username
            obj.save()

            model_obj.has_dispute = True
            model_obj.save()

            messages.success(request, success_mssg)
        else:
            messages.error(request, f"Network Error, Dispute not raised!!!")
        return redirect(redirect_url)     
    else:
        for q in query:
            if q['model_name'] == 'LINE_ANALYSIS':
                d = get_object_or_404(LineAnalysisModel, pk=q['model_id'])
                q['section'] = f'LINE {d.line}'
                q['product'] = f'{d.product} / {d.product_size} ML'
            elif q['model_name'] == 'SACHET_ANALYSIS':
                d = get_object_or_404(SachetAnalysisModel, pk=q['model_id'])
                q['section'] = f'MACHINE {d.mc_id.machine}'
                q['product'] = f'{d.product_id.product_name} / {d.product_id.product_size} ML'
            elif q['model_name'] == 'LINE INSPECTION':
                d = get_object_or_404(LineInspectionModel, pk=q['model_id'])
                q['section'] = f'LINE {d.l_id.line}'
                q['product'] = f'{d.product_id.product_name} / {d.product_id.product_size} ML'
            elif q['model_name'] == 'SACHET INSPECTION':
                d = get_object_or_404(SachetInspectionModel, pk=q['model_id'])
                q['section'] = f'MACHINE {d.mc_id.machine}'
                q['product'] = f'{d.product_id.product_name} / {d.product_id.product_size} ML'
            else:
                pass

        form = DisputeCreateForm()        
        context = {
            'data':query,
            'form':form,
            }     
    return render(request, template_name, context)






""" GET DETAIL DISPUTES / UPDATE / CLOSE """
@login_required(login_url='/login')
def dispute_detail(request, pk):
    template_name = 'dispute_detail.html'
    query = get_object_or_404(DisputeModel, pk=pk)

    if query.model_name == 'LINE_ANALYSIS':
        model_obj = get_object_or_404(LineAnalysisModel, pk=query.model_id)
        success_mssg = f'Dispute raised on Line Analysis Form DATE : {model_obj.date}, LINE : {model_obj.line}'
        redirect_url = f'/line/analysis/detail/{query.model_id}/'
        section = f'ANALYSIS FORM | LINE {model_obj.line}'
        product = f'{model_obj.product} / {model_obj.product_size} ML'
    elif query.model_name == 'SACHET_ANALYSIS':
        model_obj = get_object_or_404(SachetAnalysisModel, pk=query.model_id)
        success_mssg = f'Dispute raised on Sachet Analysis Form DATE : {model_obj.date}, MACHINE : {model_obj.mc_id.machine}'
        redirect_url = f'/sachet/analysis/detail/{query.model_id}/'
        section = f'ANALYSIS FORM | MACHINE {model_obj.mc_id.machine}'
        product = f'{model_obj.product_id.product_name} / {model_obj.product_id.product_size} ML'
    elif query.model_name == 'LINE_INSPECTION':
        model_obj = get_object_or_404(LineInspectionModel, pk=query.model_id)
        success_mssg = f'Dispute raised on Line Inspection Form DATE : {model_obj.date}, MACHINE : {model_obj.l_id.line}'
        redirect_url = f'/line/inspection/detail/{query.model_id}/'
        section = f'INSPECTION FORM | LINE {model_obj.l_id.line}'
        product = f'{model_obj.product_id.product_name} / {model_obj.product_id.product_size} ML'
    elif query.model_name == 'SACHET_INSPECTION':
        model_obj = get_object_or_404(SachetInspectionModel, pk=query.model_id)
        success_mssg = f'Dispute raised on Sachet Inspection Form DATE : {model_obj.date}, MACHINE : {model_obj.mc_id.machine}'
        redirect_url = f'/sachet/inspection/detail/{query.model_id}/'
        section = f'INSPECTION FORM | MACHINE {model_obj.mc_id.machine}'
        product = f'{model_obj.product_id.product_name} / {model_obj.product_id.product_size} ML'
    else:
        model_obj = None

    if not model_obj or model_obj == None:
        messages.error(request, f"Record not Found!!!")
        return redirect('/dispute/')

    

    if request.method == 'POST':
        
        form = DisputeCloseForm(request.POST, instance=query)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.datetime_closed = timezone.now()
            obj.status = "CLOSE"

            """ SET USER """
            obj.closed_by = request.user.username
            obj.save()

            messages.success(request, f"Dispute raised successfully")
            return redirect(redirect_url)
        else:
            messages.error(request, f"Network Error, Dispute not closed!!!")     
            return redirect(f'/dispute/detail/{pk}')     
    else:
        form = DisputeCloseForm(instance=query)        
        context = {
            'data':query,
            'form':form,
            'model_obj':model_obj,
            'section':section,
            'product':product,
            'model_mssg':success_mssg,
            'link':redirect_url
            }     
    return render(request, template_name, context)


