"""
informant_reports/ajax.py
Author: Haidar Khazen
Created 10/8/20

AJAX Functions for Informant ERP

"""
from pathlib import Path
from django.conf import settings
from django.http import JsonResponse, HttpResponse
from django.template.loader import render_to_string
from django.db.models import Subquery, OuterRef
from support.decorators import deny_get
from django.contrib.auth.models import User
from informant_erp.models import (
    InvLog, 
    InvTrx, 
    InvLoc, 
    JobLog, 
    ShipLog, 
    ShipTrx, 
    ProLog, 
    ProDetail, 
    NCMLog, 
    NCMTrx, 
    CarLoc, 
    CarInfo, 
    FrmLog, 
    FrmItem, 
    FrmDevRw, 
    FdrLog, 
    RunLog, 
    FdrExperience
    )
from informant_erp.utils import is_fdrlog_locked
from informant_lookups.models import Item, LineCompounder, LinePelletizer, Customer

@deny_get
def get_inventory_detail(request):
    slug = request.POST.get('slug', None)
    return_type = request.POST.get('return', None)
    redirect = request.POST.get('redirect', None)
    if slug is not None:
        try:
            inventory_record = InvLog.objects.annotate(car_id=Subquery(CarInfo.objects.filter(receiver=OuterRef('receiver')).values('car'))).get(slug=slug)
            if return_type != 'details':
                html = render_to_string('informant_reports/fragments/invlog_link.html', {'inventory_record': inventory_record, 'return_type': return_type, 'redirect_to': redirect})
            else:  
                transactions = InvTrx.objects.filter(receiver__slug=slug).select_related('user')
                locations = InvLoc.objects.filter(receiver__slug=slug)
                html = render_to_string('informant_reports/fragments/inv_record_detail.html', {'inventory_record': inventory_record, 'transactions': transactions, 'locations': locations})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_job_detail(request):
    slug = request.POST.get('slug', None)
    return_type = request.POST.get('return', None)
    location = request.POST.get('location', None)
    if slug is not None:
        try:
            job_record = JobLog.objects.get(slug=slug)
            if return_type == 'revise':
                html = render_to_string('informant_reports/fragments/joblog_link.html', {'joblog_record': job_record, 'return_type': return_type, 'location': location })
            else:
                html = render_to_string('informant_reports/fragments/job_record_detail.html', {'job_record': job_record,})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_ship_order_detail(request):
    slug = request.POST.get('slug', None)
    return_type = request.POST.get('return', None)
    if slug is not None:
        try:
            ship_order_record = ShipLog.objects.get(slug=slug)
            if return_type == 'revise':
                html = render_to_string('informant_reports/fragments/shiplog_link.html', {'ship_order_record': ship_order_record, 'return_type': return_type})
            else:
                transactions = ShipTrx.objects.filter(release=ship_order_record)
                html = render_to_string('informant_reports/fragments/ship_record_detail.html', {'ship_order_record': ship_order_record, 'transactions': transactions})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_item_detail(request):
    slug = request.POST.get('slug', None)
    return_type = request.POST.get('return', None)
    if slug is not None:
        try:
            item_record = Item.objects.get(slug=slug)
            if return_type == 'revise':
                html = render_to_string('informant_reports/fragments/item_link.html', {'item_record': item_record, 'return_type': return_type})
            else:
                html = render_to_string('informant_reports/fragments/item_record_detail.html', {'item_record': item_record,})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_user_detail(request):
    slug = request.POST.get('slug', None)
    return_type = request.POST.get('return', None)
    if slug is not None:
        try:
            user_record = User.objects.get(id=slug)
            if return_type == 'revise':
                html = render_to_string('informant_reports/fragments/user_link.html', {'user_record': user_record, 'return_type': return_type})
            else:
                html = render_to_string('informant_reports/fragments/user_record_detail.html', {'user_record': user_record,})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_production_detail(request):
    pk = request.POST.get('slug', None)
    return_type = request.POST.get('return', None)
    if pk is not None:
        try:
            if return_type == 'revise':
                prolog_record = ProLog.objects.get(pk=pk) 
                html = render_to_string('informant_reports/fragments/prolog_link.html', {'prolog_record': prolog_record, 'return_type': return_type})
            else:
                prolog_record = ProLog.objects.get(pk=pk)  
                downtimes = ProDetail.objects.filter(prolog=pk).select_related('code')
                html = render_to_string('informant_reports/fragments/prolog_record_detail.html', {'prolog_record': prolog_record, 'downtimes': downtimes})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_ncm_detail(request):
    slug = request.POST.get('slug', None)
    return_type = request.POST.get('return', None)
    if slug is not None:
        try:
            ncm_record = NCMLog.objects.get(slug=slug)
            if return_type == 'revise':
                html = render_to_string('informant_reports/fragments/ncm_link.html', {'ncm_record': ncm_record, 'return_type': return_type})
            else:
                transactions = NCMTrx.objects.filter(ncm=ncm_record)
                html = render_to_string('informant_reports/fragments/ncm_record_detail.html', {'ncm_record': ncm_record, 'transactions': transactions})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_formulation_detail(request):
    pk = request.POST.get('slug', None)  # Ajax call send in "slug" - use as pk
    return_type = request.POST.get('return', None)
    location = request.POST.get('location', None)
    if pk is not None:
        try:
            frmlog_record = FrmLog.objects.get(pk=pk)
            if return_type == 'approve': 
                html = render_to_string('informant_reports/fragments/frmlog_link.html', {'frmlog_record': frmlog_record, 'return_type': return_type, 'location': location, 'fdrlog_locked': is_fdrlog_locked(frmlog_record) })
            elif return_type == 'revise':
                if frmlog_record.locked_by is None:
                    html = render_to_string('informant_reports/fragments/frmlog_link.html', {'frmlog_record': frmlog_record, 'return_type': return_type, 'location': location })
                else:
                    html = render_to_string('informant_reports/fragments/frmlog_link.html', {'frmlog_record': frmlog_record, 'return_type': return_type, 'location': location, 'status': 'locked' })
            else: 
                frm_dev = FrmLog.objects.get(pk=pk).frmdev_set.all()
                frm_items = FrmItem.objects.filter(frmlog=pk).order_by('sequence')
                frm_devrws = FrmDevRw.objects.filter(frmlog=pk)
                media_url = settings.MEDIA_URL
                html = render_to_string('informant_reports/fragments/frmlog_record_detail.html', {'frmlog_record': frmlog_record, 
                                                                                                  'frm_dev': frm_dev, 
                                                                                                  'frm_items': frm_items, 
                                                                                                  'frm_devrws': frm_devrws, 
                                                                                                  'MEDIA_URL': media_url})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_feeder_setup_detail(request):
    pk = request.POST.get('slug', None)  # Ajax call send in "slug" - use as pk
    return_type = request.POST.get('return', None)
    if pk is not None:
        try:
            if return_type == 'revise':
                fdrlog_record = FdrLog.objects.get(pk=pk) 
                html = render_to_string('informant_reports/fragments/fdrlog_link.html', {'fdrlog_record': fdrlog_record, 'return_type': return_type})
            else:
                fdrlog_record = FdrLog.objects.get(pk=pk)
                frmlog_record = FrmLog.objects.get(pk=fdrlog_record.frmlog_id)
                frm_devrws = FrmDevRw.objects.filter(frmlog=fdrlog_record.frmlog_id)
                html = render_to_string('informant_reports/fragments/fdrlog_record_detail.html', {'fdrlog_record': fdrlog_record, 'frmlog_record': frmlog_record, 'frm_devrws': frm_devrws})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_run_parameter_setup_detail(request):
    pk = request.POST.get('slug', None)  # Ajax call send in "slug" - use as pk
    return_type = request.POST.get('return', None) # return detail or a link if used as a select lookup
    if pk is not None:
        try:
            if return_type == 'revise':
                runlog_record = RunLog.objects.get(pk=pk) 
                html = render_to_string('informant_reports/fragments/runlog_link.html', {'runlog_record': runlog_record, 'return_type': return_type})
            else:
                runlog_record = RunLog.objects.get(pk=pk)
                fdrlog_record = FdrLog.objects.get(pk=pk)
                # Get compounder_type and pelletizer_type based on runlog's line to congure labels and fields to display in detail
                compounder_type = LineCompounder.objects.get(line=runlog_record.line_id).compounder.type
                pelletizer_type = LinePelletizer.objects.get(line=runlog_record.line_id).pelletizer.type
                html = render_to_string('informant_reports/fragments/runlog_record_detail.html', {'runlog_record': runlog_record, 'fdrlog_record': fdrlog_record, 'compounder_type': compounder_type, 'pelletizer_type': pelletizer_type})
            return HttpResponse(html)
        except Exception as e:
            print (getattr(e, 'message', repr(e)))
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_fdr_experience_detail(request):
    pk = request.POST.get('slug', None)  # Ajax call send in "slug" - use as pk
    return_type = request.POST.get('return', None)
    if pk is not None:
        try:
            if return_type == 'revise':
                fdrexp_record = FdrExperience.objects.get(pk=pk) 
                html = render_to_string('informant_reports/fragments/fdrexp_link.html', {'fdrexp_record': fdrexp_record, 'return_type': return_type})
            else:
                fdrexp_record = FdrExperience.objects.get(pk=pk)
                html = render_to_string('informant_reports/fragments/fdrexp_record_detail.html', {'fdrexp_record': fdrexp_record,})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_car_history(request):
    car = request.POST.get('slug', None)
    return_type = request.POST.get('return', None)
    if car is not None:
        try:
            if return_type == 'revise':
                car_record = CarLoc.objects.filter(car_id=car).first()  #Get current car
                html = render_to_string('informant_reports/fragments/car_link.html', {'car_record': car_record, 'return_type': return_type})
            else:
                carloc_history = CarLoc.objects_archive.filter(car_id=car).select_related('posted_by').order_by('-posted_ts')
                carinfo_history = CarInfo.objects_archive.filter(car_id=car).select_related('posted_by').order_by('-posted_ts')
                html = render_to_string('informant_reports/fragments/car_history.html', {'carloc_history': carloc_history, 'carinfo_history': carinfo_history,})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def get_customer_detail(request):
    pk = request.POST.get('slug', None)
    return_type = request.POST.get('return', None)
    if pk is not None:
        try:
            customer_record = Customer.objects.get(pk=pk)
            if return_type == 'revise':
                html = render_to_string('informant_reports/fragments/customer_link.html', {'customer_record': customer_record, 'return_type': return_type})
            else:
                html = render_to_string('informant_reports/fragments/customer_record_detail.html', {'customer_record': customer_record})
            return HttpResponse(html)
        except:
            data = {'error': 'An error occurred'}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)

@deny_get
def job_export_file_exists(request):
    jobid = request.POST.get('job', None)
    filename_fields = request.POST.get('filename_fields', None)

    if jobid and filename_fields:
        job = JobLog.objects.get(job=jobid)

        # Generate custom filename based filename_fields
        fields = filename_fields.split('_')
        data_list = []
        for field in fields:
            data_list.append(str(getattr(job, field)))
        filename = '_'.join(data_list) + '.xlsx'

        filepath = Path(settings.MEDIA_ROOT, 'excel_templates')
        path = Path(filepath, filename)
        data = {'exists': path.is_file()}
    else:
        data = {'error': 'No Data'}
    return JsonResponse(data)
