"""
support/ajax.py
Author: Haidar Khazen
Created 2/5/21

AJAX functions used throughout app

"""

from django.apps import apps
from django.http import JsonResponse
from .decorators import deny_get

'''
 generic method to get a single value back given the  and target fields, key, model, and app
 key - search term
 app - informant_erp, etc. - default informant_lookups
 model_class - which model
 search_field - which field to search on
 target_field - which field to return
 follow - if required value in a linked table, include field name from original table that is the foreign key
 search field should contain unique data - if not, value returned = first found from list
'''

@deny_get
def get_value_from_model(request):
    key = request.POST.get('key', None)
    search_field = request.POST.get('search_field', None)
    target_field = request.POST.get('target_field', None)
    model_class = request.POST.get('model_class', None)
    app = request.POST.get('app', None)
    follow = request.POST.get('follow', None)
    manager = request.POST.get('manager', None)
    if app is None:
        TargetModel = apps.get_model('informant_lookups', model_class)
    else:
        TargetModel = apps.get_model(app, model_class)
    if key is not None:
        try:
            #if manager == 'SYS':
            #    result = TargetModel.objects_sys.filter(**{search_field: key}).first()
            #else:
            #    result = TargetModel.objects.filter(**{search_field: key}).first()
            if manager is None:
                manager = 'objects'  # Use standard manager if not defined in call
            result = getattr(TargetModel, manager).filter(**{search_field: key}).last() # last() gets single result, latest entered
            if follow is not None:  # Follow FK relationship
                value = getattr(getattr(result, target_field), follow)  #Usage: target_field full object (not _id), field name to follow
            else:
                value = getattr(result, target_field)
            field_type = TargetModel._meta.get_field(target_field).__class__.__name__
            if field_type == 'FileField':
                data = {
                    'value': value.name,
                     'found': True,
                     }
            else:
                data = {
                    'value': value,
                     'found': True,
                     }
        except:
            data = {
                'value': 'not-found',
                'found': False,
                }
    else:
        data = {
            'value': 'no-key',
            'found': False,
            }
    return JsonResponse(data)

# Generic ajax function to return slug, existance of a record, and index if needed
#   class_name - the name of the model class that holds the record
#   search_field - the name of the field to search for the record - defaults to 'name'
#   app - the app in which the model is (informant_erp, etc.  defaults to informant_lookups)
#   key - data value for which to search
#   get_index - if this is 'True', iterate through the queryset to get the index of the item
@deny_get
def get_slug(request):
    key = request.POST.get('key', None)
    model_class = request.POST.get('model_class', None)
    search_field = request.POST.get('search_field', 'name')
    app = request.POST.get('app', None)
    if app is None:
        TargetModel = apps.get_model('informant_lookups', model_class)
    else:
        TargetModel = apps.get_model(app, model_class)
    index_required = request.POST.get('get_index', False)
    if key is not None:
        try:
            index = 0
            if index_required:
                record_list = TargetModel.objects.all().order_by(search_field)
                for record in record_list:
                    if getattr(record, search_field, 'name') == key:  #getattr is like record.{search_field}
                        break
                    index += 1
            item = TargetModel.objects.get(**{search_field: key})
            data = {'slug': item.slug, 'idx': index}
        except:
            data = {'slug': 'not-found'}
    else:
        data = {'slug': 'not-found'}
    return JsonResponse(data)
