from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.contrib.auth.models import AnonymousUser
from . import reports as base_reports  
from baseapp.internal import localfunc
from . import initalconfig
from .models import  country_state,  tags, patient, employee,disease,task,treatment,Zone,gender,Master_GST,District_State,Zone_Type,Zone_System,ID_type, User_Group
from django.shortcuts import render,redirect
import requests, csv, json, base64
from django.contrib.auth.decorators import login_required
from datetime import datetime as dt
from .forms import form_District_State, form_tags, form_tags_search, form_District_State_search,form_patient, form_gender,form_gender_search,form_employee, form_employee_search
from .forms import  form_Zone_System,form_patient_search,form_Master_GST,form_ID_type,form_ID_type_search, form_User_Group, form_User_Group_search
#from .forms import form_login_captcha
from .forms import  form_disease,form_disease_search,form_task,form_task_search,form_treatment,form_treatment_search,form_zone,form_zone_search, form_report_base,form_Master_GST_search,form_Zone_System_search,form_Zone_Type,form_Zone_Type_search
from .forms import  form_report_base, form_report_employ, form_report_stock_check
from django.contrib.auth.models import User
from django.utils.http import url_has_allowed_host_and_scheme
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from baseapp.internal import refactor
from help.models import instruction
from datetime import datetime
import logging
from django.urls import reverse
from diagnoses.models import condition, diagnose,disease_details
from consult.models import blood_Pressure, nutritional_value,vitals, History_examination, observation,scheduling,treatment_details
from medic.models import medications,inventory_entry,medic_inhouse
from django.db.models.functions import TruncMonth, TruncDate
from django.db.models import Count, Sum
logger = logging.getLogger('django')




def error_500_view(request):
    exception = ''
    messages.error(request, exception +'Please check the Error, if it repeats contact Site Administrator.')
    print(request.build_absolute_uri())
    
    return redirect (request.build_absolute_uri()) # HttpResponseRedirect (request.build_absolute_uri())    

def view_nav_emplo(request):    return render(request,'desktop/emplo_desk_nav.html')

def view_nav_patient(request):    return render(request,'desktop/patient_desk_nav.html')

def lf_patient_summary(pid):
   total_condition = 0; total_diagnose = 0; total_bp =  0; total_fees  =  0; total_nutrition =  0; total_vitals  =  0; total_medic = 0; total_exam = 0;total_observation=0;total_disease_details=0;total_med_unit=0;total_medic_inhouse=0;total_inventory_entry=0;total_scheduling = 0;total_treatment_details=0
   if  patient.objects.filter(pk = pid).exists():
        obj_patient = patient.objects.get(pk = pid)
        if condition.objects.filter(fk_patient = obj_patient).exists(): total_condition =  condition.objects.filter(fk_patient = obj_patient ).count()
        if diagnose.objects.filter(fk_patient = obj_patient).exists(): total_diagnose =  diagnose.objects.filter(fk_patient = obj_patient ).count()
        if medications.objects.filter(fk_patient = obj_patient).exists(): total_medic =  medications.objects.filter(fk_patient = obj_patient ).count()

        #if med_unit.objects.filter(fk_patient = obj_patient).exists(): total_med_unit =  med_unit.objects.filter(fk_patient = obj_patient ).count()
       # if medic_inhouse.objects.filter(fk_patient = obj_patient).exists(): total_medic_inhouse =  medic_inhouse.objects.filter(fk_patient = obj_patient ).count()
#        if inventory_entry.objects.filter(fk_patient = obj_patient).exists(): total_inventory_entry =  inventory_entry.objects.filter(fk_patient = obj_patient ).count()
        if observation.objects.filter(fk_patient = obj_patient).exists(): total_observation =  observation.objects.filter(fk_patient = obj_patient ).count()
        if blood_Pressure.objects.filter(fk_patient = obj_patient).exists(): total_bp =  blood_Pressure.objects.filter(fk_patient = obj_patient ).count()
        if disease_details.objects.filter(fk_patient = obj_patient).exists(): total_disease_details =  disease_details.objects.filter(fk_patient = obj_patient ).count()

        if scheduling.objects.filter(fk_patient = obj_patient).exists(): total_scheduling =  scheduling.objects.filter(fk_patient = obj_patient ).count()

        if treatment_details.objects.filter(fk_patient = obj_patient).exists(): total_treatment_details =  treatment_details.objects.filter(fk_patient = obj_patient ).count()

        if nutritional_value.objects.filter(fk_patient = obj_patient).exists(): total_nutrition =  nutritional_value.objects.filter(fk_patient = obj_patient ).count()
        if vitals.objects.filter(fk_patient = obj_patient).exists(): total_vitals =  vitals.objects.filter(fk_patient = obj_patient ).count()
        if History_examination.objects.filter(fk_patient = obj_patient).exists(): total_exam =  History_examination.objects.filter(fk_patient = obj_patient ).count()

   return {'total_condition': total_condition, 'total_diagnose': total_diagnose, 'total_bp': total_bp, 'total_fees': total_fees, 'total_nutrition': total_nutrition, 'total_vitals' : total_vitals, 'total_medic': total_medic, 'total_exam': total_exam, 'total_observation': total_observation, 'total_disease_details': total_disease_details,'total_med_unit':total_med_unit,'total_medic_inhouse':total_medic_inhouse,'total_inventory_entry':total_inventory_entry,'total_scheduling':total_scheduling,'total_treatment_details':total_treatment_details}


# def lf_datefix(list_data, list_datefields = []):
#     for single_entry in list_data:
#         for single_date in list_datefields:
#             single_entry[single_date] = single_entry[single_date].strftime("%d-%m-%y")
#     return list_data
def lf_datefix(list_datefields = []):
        list_output = []
        for single_date in list_datefields:list_output.append(single_date.strftime("%d-%m-%y")) 
        return list_output

def lf_dash_location_summary():
   data_summary = {}
   obj_patient =  patient.objects.annotate(entry_date=TruncDate('date_modified')).values('entry_date').annotate(patients=Count('id'))     # Truncate to month and add to select list
   list_tuple = obj_patient.values_list('patients','entry_date')
   data_summary['data_patient'] = {'patients' : list(map(lambda x: x[0], list_tuple) )  ,'entry_date' : lf_datefix(list(map(lambda x: x[1], list_tuple)) )  }


   
   return    data_summary                         # Group By month
                        # Select the count of the grouping
 #       .order_by()
    # patient.objects.all().count()
    # pass



def page_logout(request):
    logout(request)    
    return redirect(reverse('base:view_login'))

@login_required
def formview_mob_patient(request, id = 0):    
    #print(request.META['HTTP_USER_AGENT'] )
    if 'Mobile' in request.META['HTTP_USER_AGENT']: 
        pass        #print('This is Mobile')
    return formview_mob_base(request,form_patient,patient, 'Patient',id, 'add_patient')
@login_required
def view_mob_base(request,obj_model,form_search, list_filter=[],list_view=[], str_name ='',viewtype ='tbl'):
    str_path = request.path
    str_path_parent = str_path.replace(str_path.split('/')[len(str_path.split('/'))-1],'')
    editurl = str_path_parent + 'form/'
    baseurl = str_path_parent + 'api'
    deleteurl = str_path_parent + 'delete/'
    #print(str_path_parent)
    if request.method == "GET":
        dic_filter = lf_get_filterdic(request, list_filter)
        obj_data = obj_model.objects.filter(**dic_filter)# one time filter
        int_recordcount = obj_data.count()
        if viewtype =='api' and request.GET.get('order'):
            if request.GET.get('order') == 'asc': obj_data = obj_data.order_by(request.GET.get('sort'))
            if request.GET.get('order') == 'desc': obj_data = obj_data.order_by('-' +request.GET.get('sort'))
        if request.GET.get('search') and viewtype =='api': # add additional filter for  api key and also sorting
            obj_data = obj_data.filter(code_iso__icontains = request.GET.get('search') )
            if request.GET.get('limit') : obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse(lf_gettbl(obj_data,obj_data.count(), int_recordcount), safe=False)
        
        elif request.GET.get('limit')  and viewtype =='api':      
            obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse(lf_gettbl(obj_data,int_recordcount,int_recordcount), safe=False)
        elif viewtype =='api': return JsonResponse(lf_gettbl(obj_data,int_recordcount,int_recordcount), safe=False)
        elif viewtype =='csv': return lf_getcsv(obj_data,str_name)
        elif viewtype =='tbl': 
            form1 = form_search(request.GET)
            context = {'jsoncolumn' : lf_get_tbl_clmn(obj_model,list_view), 'tblname': str_name +' List', 'title': str_name + ' List View', 'baseurl': baseurl+'?' +lf_get_filterdic_req(dic_filter), 'editurl': editurl, 'form':form1}
            return render(request,'base/view_tbl_mob.html', context)
            #return render(request,'baseapp/tbl_bs2_tag.html', context)
        else: return HttpResponseRedirect('/')
    else: return HttpResponseRedirect('/')

@login_required
def view_mob_patient(request,viewtype ='tbl',*args, **kwargs):
    return view_mob_base(request,patient,form_patient_search,form_patient.Meta.fields ,form_patient.Meta.fields, 'patient',viewtype)


# def view_mob_patient(request):
#     return render()

@login_required
def formview_mob_base(request, obj_form, obj_inst, obj_name,id = 0, help_id= ''):
    if  request.user.is_authenticated and request.user.is_staff: 
        obj_help =''    #messages.success(request, 'welcome <b>' + request.user.username + '</b>, to Django Development', 'success')
        if instruction.objects.filter( uid = help_id).exists():  obj_help = instruction.objects.filter( uid = help_id)[0]
        #print(request.path)
        if  request.method == "GET": 
            if id == 0 : # if there is a new form need to be updated
                form = obj_form() 
                messages.info(request, 'New Form, Please enter your delails')
                context = {'title': 'Add New ' + obj_name +' details', 'form':form, 'obj_help': obj_help}                 
            # if the data is not available
            elif obj_inst.objects.filter(id=id).exists() == False: return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))
            else:
                form =  obj_form(instance= obj_inst.objects.get(id=id))
                messages.warning(request, 'Edit Form, Please Check details properly before submit')
                context = {'title': 'Edit ' + obj_name +' details - ' + obj_inst.objects.get(id=id).__str__(), 'form':form }
        elif request.method == "POST":
           if id == 0 : form = obj_form(request.POST or None)  # if there in a new  form
           else: form = obj_form(request.POST or None,instance= obj_inst.objects.get(id=id))  # for editing instance shuold be added
           if form.is_valid():
              if id == 0 : 
                  try: 
                      obj_inst.objects.create(**form.cleaned_data) # for new entry 
                      messages.success(request, "Your Entry has been updated")
                      form = obj_form() 
                  except Exception as err: messages.error(request, str(err), 'danger')  

                  context = {'title': 'Add New ' + obj_name +' details', 'form':form }
              else :  
                  form.save() # for edit
                  messages.success(request, "Profile details updated.")
                  #print(request.path.replace('/'+ str(id), '0')+'test redirect')
                  return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))
           else: 
               messages.error(request, form.errors, 'danger')
               context = {'title':  obj_name +' Errors in form: please check details', 'form':form }
        return render(request, "base/view_mob_width.html", context)  
    else:
        return redirect("/") 

# def lf_get_filterdic(request, list_filter):
#     filter_string = {}
#     for str_filter in list_filter:
#         if request.GET.get(str_filter) :
#             if str_filter[:2] == 'fk' and  request.GET.get(str_filter) ==0 :  pass # if fk with 0 then do not add filter 
#             else: filter_string[str_filter] =  request.GET.get(str_filter)
#     print(filter_string)
#     return filter_string
def lf_get_filterdic(request, list_filter):
    filter_string = {}
    for str_filter in list_filter:
        if request.GET.get(str_filter) :
            if request.GET.get(str_filter).isnumeric():   
                if request.GET.get(str_filter) != '0': filter_string[str_filter] =  request.GET.get(str_filter)
            else:                                          filter_string[str_filter+ '__icontains'] =  request.GET.get(str_filter)
        elif request.GET.get(str_filter+ '__icontains') :
            filter_string[str_filter+ '__icontains'] =  request.GET.get(str_filter+ '__icontains')

    #print(filter_string)
    return filter_string
def lf_get_filterdic_req(dic_filter):
    str_group = ''
    for str_key in list(dic_filter.keys()): 
        str_group += str_key + '='+ dic_filter[str_key] +'&'
    return str_group



def lf_get_tbl_clmn_name_list(obj_model):
     json_clmn = []
     for obj_model_field in obj_model._meta.get_fields():
         if obj_model_field.is_relation == False and obj_model_field.name != 'id':json_clmn.append(obj_model_field.name)
     #print(json_clmn, 'table columns')
     return json_clmn

def lf_get_fkfield_list(obj_model):
     json_clmn = []
     for obj_model_field in obj_model._meta.get_fields():
         if obj_model_field.is_relation == True and obj_model_field.name[0:2] == 'fk' :json_clmn.append(obj_model_field.name)
     return json_clmn



def lf_get_tbl_clmn(obj_model, view_list = []):            # for each loop check it is relation and get the name and title name for table view 
    json_clmn = []
    for str_field in  view_list:
        if  obj_model._meta.fields: 
            obj_fileds = obj_model._meta.get_fields()
        else:
             obj_fileds = obj_model.get_fields()
        for obj_model_field in obj_fileds:
            if str_field == obj_model_field.name:    
                json_clmn.append({
                    'header': obj_model_field.name,
                    'title': obj_model_field.verbose_name ,
                })
    return json_clmn


def lf_getcsv( obj_data, str_file = 'report', list_dt=[], list_Optional = [] ):
        # file name, date fields and Optional Fields 
        response = HttpResponse(content_type='text/csv', #.values()) # default unfiltered 
        headers={'Content-Disposition':'attachment; filename="'+ str_file + '_' + dt.now().strftime("%d-%m-%y_%H-%M") + '.csv"'}, )
        writer = csv.writer(response)

        if obj_data.exists():
            list_data = obj_data.values_list() # get list of data in tuples
            json_header = list(obj_data.values()[0])    # get one set of data for header in dictionary format
            writer.writerow(json_header) # write header once
            if list_dt or list_Optional: list_data = list(obj_data.values())# get list of data in dictionary
            for single_entry in list_data:
                if list_dt: 
                    for datefield in list_dt: single_entry[datefield] =single_entry[datefield].strftime("%Y-%m-%d")  # uploadable format
                if list_Optional:
                    for field_optional in list_Optional: 
                        if single_entry[field_optional]  is  None: single_entry[field_optional]   = ''
                #print(single_entry)
                #print(type(single_entry))
                if type(single_entry) == tuple : writer.writerow(single_entry) # for tuples
                else: writer.writerow(list(single_entry.values())) # for dicitonary
        else:writer.writerow('No Data Found') 

        return response

# def lf_gettbl_disease( obj_data,int_total,int_totalwofilter  ,  list_dt=[], list_Optional = []):
#         index = 0; list_data = {"total":int_total,"totalNotFiltered":int_totalwofilter}
#         if obj_data.exists():
#             list_data['rows'] = list(obj_data.values())# get list of data in dictionary
#             for single_entry in list_data['rows']:
#                 for datefield in list_dt:                    single_entry[datefield] =single_entry[datefield].strftime("%Y-%m-%d")  # uploadable format
#                 for field_optional in list_Optional:                        
#                         if single_entry[field_optional]  is  None: single_entry[field_optional]   = ''
#                 single_entry['fk_disease'] =  obj_data[index].fk_disease.disease_name  
#                 index +=1
#         else: list_data = [{'status':'nodata'}]
#         return list_data

# def cf_rel_api_disease(obj_data,list_data):
#     index = 0
#     if list_data['rows']:
#         for single_entry in list_data['rows']:     
#             single_entry['fk_disease'] =  obj_data[index].fk_disease.disease_name; index +=1
#     return list_data
# def cf_rel_api_treatment(obj_data,list_data):
#     index = 0
#     if list_data['rows']:
#         for single_entry in list_data['rows']:     
#             single_entry['fk_treatment'] =  obj_data[index].fk_treatment.treatment_name; index +=1
#     return list_data

# def cf_rel_api_medinvent(obj_data,list_data):
#     index = 0
#     if list_data['rows']:
#         for single_entry in list_data['rows']:     
#             single_entry['fk_med'] =  obj_data[index].fk_med.drug_name; index +=1
#     return list_data
# def cf_rel_api_fk_zone(obj_data,list_data):
#     index = 0
#     if list_data['rows']:
#         for single_entry in list_data['rows']:     
#             single_entry['fk_zone'] =  obj_data[index].fk_zone.center; index +=1
#     return list_data


# def cf_rel_api_fk_med(obj_data,list_data):
#     index = 0
#     if list_data['rows']:
#         for single_entry in list_data['rows']:     
#             single_entry['fk_med'] =  obj_data[index].fk_med.drug_name; index +=1
#     return list_data

# def cf_rel_api_fk_gender(obj_data,list_data):
#     index = 0
#     if list_data['rows']:
#         for single_entry in list_data['rows']:     
#             single_entry['fk_gender'] =  obj_data[index].fk_gender.gender_name; index +=1
#     return list_data

# def cf_rel_api_fk_employee(obj_data,list_data):
#     index = 0
#     if list_data['rows']: 
#         for single_entry in list_data['rows']: 
#             single_entry['applyto_employee'] =  obj_data[index].applyto_employee.str_username; index +=1
#     return list_data

# def cf_rel_api_Zone(obj_data,list_data):
#     index = 0
#     if list_data['rows']: 
#         for single_entry in list_data['rows']: 
#             single_entry['fk_System'] =  obj_data[index].fk_System.System
#             single_entry['fk_Type'] =  obj_data[index].fk_Type.Ztype
#             single_entry['fk_District'] =  obj_data[index].fk_District.District; index +=1
#     return list_data


def cf_rel_api_fk_fields(obj_model, obj_data,list_data):
    list_fields = []
    for obj_field in obj_model._meta.get_fields(): list_fields.append(obj_field.name)
    #print(list_fields)
    index = 0
    if list_data['rows']: 
        for single_entry in list_data['rows']: 
            if 'fk_System' in list_fields and obj_data[index].fk_System is not None : single_entry['fk_System'] =  obj_data[index].fk_System.System
            if 'fk_system' in list_fields and obj_data[index].fk_system is not None : single_entry['fk_system'] =  obj_data[index].fk_system.System
            if 'fk_Type' in list_fields and obj_data[index].fk_Type is not None : single_entry['fk_Type'] =  obj_data[index].fk_Type.Ztype
            if 'fk_District' in list_fields and obj_data[index].fk_District is not None : single_entry['fk_District'] =  obj_data[index].fk_District.District
            if 'fk_dist' in list_fields and obj_data[index].fk_dist is not None : single_entry['fk_dist'] =  obj_data[index].fk_dist.District
            if 'proof' in list_fields and obj_data[index].proof is not None : single_entry['proof'] =  obj_data[index].proof.name
            if 'applyto_employee' in list_fields and obj_data[index].applyto_employee is not None : single_entry['applyto_employee'] =  obj_data[index].applyto_employee.str_username
            if 'fk_gender' in list_fields and obj_data[index].fk_gender is not None : single_entry['fk_gender'] =  obj_data[index].fk_gender.gender_name
            if 'fk_disease' in list_fields and obj_data[index].fk_disease is not None : single_entry['fk_disease'] =  obj_data[index].fk_disease.disease_name
            if 'fk_treatment' in list_fields and obj_data[index].fk_treatment is not None : single_entry['fk_treatment'] =  obj_data[index].fk_treatment.treatment_name
            if 'fk_zone' in list_fields and obj_data[index].fk_zone is not None : single_entry['fk_zone'] =  obj_data[index].fk_zone.center
            if 'fk_med' in list_fields and obj_data[index].fk_med is not None : single_entry['fk_med'] =  obj_data[index].fk_med.drug_name
            if 'fk_GST' in list_fields and obj_data[index].fk_GST is not None : single_entry['fk_GST'] =  obj_data[index].fk_GST.gst_shorttext
            
            if 'profile_pic' in list_fields and obj_data[index].profile_pic is not None : single_entry['profile_pic'] = '<img src="/'+   str(obj_data[index].profile_pic) + '" style=" hieght:80px width:80px" alt="Photo Missing" class="image">'
            
            

            index +=1
    return list_data




def lf_gettbl( obj_data,int_total,int_totalwofilter  ,  list_dt=[], list_Optional = [], list_time = []):
        # file name, date fields and Optional Fields (optional field total records without pagination)
        list_time =  ['time_duration']
        print(list_dt, 'time fields' , list_time)
        list_data = {"total":int_total,"totalNotFiltered":int_totalwofilter}
        if obj_data.exists():
            list_data['rows'] = list(obj_data.values())# get list of data in dictionary
            #if list_dt and list_Optional:
            for single_entry in list_data['rows']:
                for datefield in list_dt:      
                    if  datefield in single_entry.keys(): single_entry[datefield] =single_entry[datefield].strftime("%Y-%m-%d")  # uploadable format
                for timefield in list_time:      
                    if  timefield in single_entry.keys():                         single_entry.update( {timefield: str(single_entry[timefield])  } )   # uploadable format    
                for field_optional in list_Optional:                        
                        if single_entry[field_optional]  is  None: single_entry[field_optional]   = ''
        else: list_data = [{'status':'nodata'}]
        #print(list_data)
        return list_data

@login_required
def formview_base(request, obj_form, obj_inst, obj_name,id = 0,help_id= ''):
    if  request.user.is_authenticated and request.user.is_staff: 
        if employee.objects.filter(str_username = request.user.username).exists(): obj_emp = employee.objects.filter( str_username = request.user.username)[0]
        obj_help =''    
        if instruction.objects.filter( uid = help_id).exists():            obj_help = instruction.objects.filter( uid = help_id)[0]
        context = {'title': 'Add New ' + obj_name +' details','obj_help':obj_help}     
        if  request.method == "GET": 
            if id == 0 : # if there is a new form need to be updated
                form = obj_form() ; context['form'] = form
                messages.info(request, 'New Form, Please enter your delails')
            
            elif obj_inst.objects.filter(id=id).exists() == False: return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))# if the data is not available
            else: # edit an entry
                form =  obj_form(instance= obj_inst.objects.get(id=id))
                messages.warning(request, 'Edit Form, Please Check details properly before submit')
                context['title']= 'Edit ' + obj_name +' details - ' + obj_inst.objects.get(id=id).__str__();context['form']= form 
        elif request.method == "POST":
           if id == 0 : form = obj_form(request.POST or None)  # if there in a new  form
           else: form = obj_form(request.POST or None,instance= obj_inst.objects.get(id=id))  # for editing instance shuold be added
           if form.is_valid():
              list_model = ['Zone', 'Zone_System', 'Zone_Type',"District_State","ID_type"] # exception models to enter employee fk key
              # str(obj_model.__name__).strip() 
              if id == 0 : # for new entry 
                  try:  # if entry has employee field
                      if employee.objects.filter(str_username = request.user.username).exists() and str(obj_inst.__name__).strip() not in list_model:
                          obj_inst.objects.create(**form.cleaned_data, fk_employee = obj_emp) 
                      else:   obj_inst.objects.create(**form.cleaned_data) 
                      messages.success(request, "Your Entry has been updated")
                      form = obj_form() 
                  except Exception as err: messages.error(request, str(err), 'danger')  
                  context['title']= 'Add New ' + obj_name +' details'; context['form'] = form 
              else :  # for edit
                  form.save();                  messages.success(request, "Profile details updated.")
                  return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))
           else: 
               context['form'] = form;context['title'] =  obj_name +' Errors in form: please check details';  messages.error(request, form.errors, 'danger')
        return render(request, "base/view_form.html", context)  
    else:
        return redirect("/") 

@login_required
def formview_base_patient(request, obj_form, obj_inst, obj_name,pid,id = 0,help_id=''):
   # print(request.GET)
    if patient.objects.filter(pk=pid).exists() and employee.objects.filter(str_username = request.user.username).exists(): 
        obj_pt = patient.objects.get(pk=pid)
        obj_emp = employee.objects.filter( str_username = request.user.username)[0]
    else:
        return HttpResponseRedirect(reverse('base:view_login'))
    if  request.user.is_authenticated and request.user.is_staff: 
        obj_help =''    
        if instruction.objects.filter( uid = help_id).exists(): 
            obj_help = instruction.objects.filter( uid = help_id)[0]
        if  request.method == "GET": 
            if id == 0 : # if there is a new form need to be updated
                form = obj_form() 
                messages.info(request, 'New Form, Please enter your delails')
                context = {'title': 'Add New ' + obj_name +' details', 'form':form,'obj_help': obj_help, 'patentid' : pid}                 
            # if the data is not available
            elif obj_inst.objects.filter(id=id).exists() == False: return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))
            else:
                form =  obj_form(instance= obj_inst.objects.get(id=id))
                messages.warning(request, 'Edit Form, Please Check details properly before submit')
                context = {'title': 'Edit ' + obj_name +' details - ' + obj_inst.objects.get(id=id).__str__(), 'form':form , 'obj_help': obj_help, 'patentid' : pid}
        elif request.method == "POST":
            
           if id == 0 : form = obj_form(request.POST or None,request.FILES)  # if there in a new  form
           else: form = obj_form(request.POST or None,request.FILES,instance= obj_inst.objects.get(id=id))  # for editing instance shuold be added
           #print(form.__dict__)# temp for debug
           
           #print(request.POST)
           if form.is_valid():
              print(form.cleaned_data)
              if id == 0 : 
                  try: 
                      if r'consultation/nutrition' in  request.path: 
                        dbl_base =  float(form.cleaned_data.get('height') )   /100                   
                        dbl_BMI = float( form.cleaned_data.get('weight') )/(dbl_base*dbl_base)
                        obj_inst.objects.create(**form.cleaned_data, fk_patient = obj_pt, fk_employee = obj_emp, BMI = dbl_BMI) # for new entry  
                      else: obj_inst.objects.create(**form.cleaned_data, fk_patient = obj_pt, fk_employee = obj_emp) # for new entry 
                      messages.success(request, "Your Entry has been updated")
                      form = obj_form() 
                      return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))     
                  except Exception as err: messages.error(request, str(err), 'danger')  
                  context = {'title': 'Add New ' + obj_name +' details', 'form':form, 'obj_help': obj_help,'patentid' : pid }
             
              else :  
                  form.save() # for edit
                  messages.success(request, "successfully details updated.")
                  return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))
           else: 
            #    if r'consultation/nutrition' in  request.path and 'maximum recursion depth exceeded ' in  form.errors: # known error
            #       form.save() # for edit
            #       messages.success(request, "successfully details updated.")
            #       return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))
            #    else:
                messages.error(request, form.errors, 'danger')
                context = {'title':  obj_name +' Errors in form: please check details', 'form':form, 'obj_help': obj_help,'patentid' : pid }
        return render(request, "base/view_form.html", context) 
    else:
        return redirect("/") 
 
 



# Create your views here.
@login_required
def Admin_Account_Creation(request):
    # update the inital data to the database
    str_username = 'sadmin'
    str_email = 'dummyemail@gs.cok'
    str_password = 'S@dmin@123'   # refactor.get_password()
     
    #create_obj = False
    
    if User.objects.filter(username=str_username).exists() == False:
        obj_user = User.objects.create_superuser(str_username, str_email,str_password)
        #print(obj_user)
        login(request, obj_user) 
        return HttpResponse('Your Admin Account has been created</br></br> Username:'+ str_username +'</br> Password:' +str_password )
    return HttpResponseRedirect('/admin')

# Create your views here.
@login_required
def init_updatedata(request):
    # update the inital data to the database  
    initalconfig.update_inital_data_country_details()   # table country_details
    initalconfig.update_inital_data_currency_code()
    initalconfig.update_inital_data_tags()
    initalconfig.update_inital_data_country_state()
    return HttpResponse('Intial data got updated, please refresh page for login')    
def test_update(request,*args,**kwargs):
    if request.method == "GET":
        str_sheet = request.GET.get('model')
        initalconfig.run_test_data(str_sheet)
        return HttpResponse('Test data for '+ str_sheet +' got updated')
    

def home_page(request):
    return HttpResponse(request.user.username)
@login_required
def view_base_delete(obj_model,request,id):
    if request.user.is_authenticated and request.user.is_staff:
        if obj_model.objects.filter(pk = id).exists():
            obj_model.objects.get(pk = id).delete()
            return HttpResponse('success')
        else:return HttpResponse('nodata')
    else:return HttpResponse('noauth')

   # return HttpResponseRedirect(str_path_parent + 'tbl')
@login_required
def view_base(request,obj_model,form_search, list_filter=[],list_view=[], str_name ='',viewtype ='tbl', str_search = '',help_id=''):
    str_path = request.path
    str_path_parent = str_path.replace(str_path.split('/')[len(str_path.split('/'))-1],'')
    editurl = str_path_parent + 'form/'
    baseurl = str_path_parent + 'api'
    deleteurl = str_path_parent + 'delete/'

    if  request.user.is_authenticated and request.user.is_staff: 
        if instruction.objects.filter( uid = help_id).exists():             obj_help = instruction.objects.filter( uid = help_id)[0]
        else: obj_help =''
    #print(str_path_parent)
    if request.method == "GET":
        dic_filter = lf_get_filterdic(request, list_filter)
        #print(dic_filter)
        obj_data = obj_model.objects.filter(**dic_filter)# one time filter
        obj_data  = obj_data.order_by('-id')
        int_recordcount = obj_data.count()
        if viewtype =='api' and request.GET.get('order'):
            if request.GET.get('order') == 'asc': obj_data = obj_data.order_by(request.GET.get('sort'))
            if request.GET.get('order') == 'desc': obj_data = obj_data.order_by('-' +request.GET.get('sort'))
        if request.GET.get('search') and viewtype =='api': # add additional filter for  api key and also sorting
            filter_search =  {str_search + '__icontains':request.GET.get('search')}
            obj_data = obj_data.filter(**filter_search)
            if request.GET.get('limit') : obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse( cf_rel_api_fk_fields(obj_model, obj_data,lf_gettbl(obj_data,obj_data.count(), int_recordcount)), safe=False)
        elif request.GET.get('limit')  and viewtype =='api':      
            obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse( cf_rel_api_fk_fields(obj_model, obj_data ,lf_gettbl(obj_data,int_recordcount,int_recordcount)), safe=False)
        elif viewtype =='api':             return JsonResponse(cf_rel_api_fk_fields(obj_model, obj_data,lf_gettbl(obj_data,int_recordcount,int_recordcount)), safe=False) 
        elif viewtype =='csv': return lf_getcsv(obj_data,str_name)
        elif viewtype =='tbl': 
            form1 = form_search(request.GET)
            context = {'jsoncolumn' : lf_get_tbl_clmn(obj_model,list_view), 'tblname': str_name +' List', 'title': str_name + ' List', 'baseurl': baseurl+'?' +lf_get_filterdic_req(dic_filter), 'editurl': editurl, 'form':form1, 'obj_help' : obj_help}
            return render(request,'base/tbl_bs.html', context)
        else: return HttpResponseRedirect('/')
    else: return HttpResponseRedirect('/')

@login_required
def view_base_patient_list(request,obj_model,form_search, list_filter=[],list_view=[], str_name ='',viewtype ='tbl',help_id='', str_search = ''):
    str_path = request.path
    str_path_parent = str_path.replace(str_path.split('/')[len(str_path.split('/'))-1],'')
    editurl =  reverse('base:patient_details') #str_path_parent + 'form/'
    viewurl = reverse('base:patient_details') 
    #print(viewurl)
    baseurl = str_path_parent + 'api'
    deleteurl = str_path_parent + 'delete/'

    if  request.user.is_authenticated and request.user.is_staff: 
        obj_help =''    #messages.success(request, 'welcome <b>' + request.user.username + '</b>, to Django Development', 'success')
        if instruction.objects.filter( uid = help_id).exists(): 
            obj_help = instruction.objects.filter( uid = help_id)[0]

    #print(str_path_parent)
    if request.method == "GET":
        dic_filter = lf_get_filterdic(request, list_filter)
        obj_data = obj_model.objects.filter(**dic_filter)# one time filter
        obj_data  = obj_data.order_by('-id')
        int_recordcount = obj_data.count()
        if viewtype =='api' and request.GET.get('order'):
            if request.GET.get('order') == 'asc': obj_data = obj_data.order_by(request.GET.get('sort'))
            if request.GET.get('order') == 'desc': obj_data = obj_data.order_by('-' +request.GET.get('sort'))
        if request.GET.get('search') and viewtype =='api': # add additional filter for  api key and also sorting
            filter_search =  {str_search + '__icontains':request.GET.get('search')}
            obj_data = obj_data.filter(**filter_search)
            if request.GET.get('limit') : obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse(cf_rel_api_fk_fields(obj_model,obj_data, lf_gettbl(obj_data,obj_data.count(), int_recordcount)), safe=False)
            
        elif request.GET.get('limit')  and viewtype =='api':      
            obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse(cf_rel_api_fk_fields(obj_model,obj_data, lf_gettbl(obj_data,int_recordcount,int_recordcount)), safe=False)
        elif viewtype =='api': return JsonResponse(cf_rel_api_fk_fields(obj_model, obj_data, lf_gettbl(obj_data,int_recordcount,int_recordcount)), safe=False)
        elif viewtype =='csv': return lf_getcsv(obj_data,str_name)
        elif viewtype =='tbl': 
            form1 = form_search()#form_search(request.GET)
            context = {'jsoncolumn' : lf_get_tbl_clmn(obj_model,list_view), 'tblname': str_name +' List', 'title': str_name + ' List ', 'baseurl': baseurl+'?' +lf_get_filterdic_req(dic_filter), 'editurl': editurl, 'viewurl': viewurl,'form':form1, 'obj_help' : obj_help}
            return render(request,'base/tbl_bs_patient_list.html', context)
            #return render(request,'baseapp/tbl_bs2_tag.html', context)
        else: return HttpResponseRedirect('/')
    else: return HttpResponseRedirect('/')
@login_required
def view_base_patient(request,obj_model,form_search,pid, list_filter=[],list_view=[], str_name ='',viewtype ='tbl',help_id='', str_search = ''):
    list_dt = ['date_created','date_modified']#,'date_scheduled'
    list_time_format  = ['time_duration']
    if patient.objects.filter(pk=pid).exists() and employee.objects.filter(str_username = request.user.username).exists(): 
        obj_pt = patient.objects.get(pk=pid)
    else: pass # go to login / home page
    obj_data = obj_model.objects.filter(fk_patient = obj_pt)# patient filter
    str_path = request.path
    str_path_parent = str_path.replace(str_path.split('/')[len(str_path.split('/'))-1],'')
    editurl = str_path_parent + 'form/'
    baseurl = str_path_parent + 'api'
    deleteurl = str_path_parent + 'delete/'

    
    if  request.user.is_authenticated and request.user.is_staff: 
        obj_help =''    #messages.success(request, 'welcome <b>' + request.user.username + '</b>, to Django Development', 'success')
        if instruction.objects.filter( uid = help_id).exists(): 
            obj_help = instruction.objects.filter( uid = help_id)[0]

    #print(str_path_parent)
    if request.method == "GET":
        dic_filter = lf_get_filterdic(request, list_filter)
        #print(dic_filter)
        obj_data = obj_data.filter(**dic_filter)# one time filter
        obj_data  = obj_data.order_by('-id')
        int_recordcount = obj_data.count()
        if viewtype =='api' and request.GET.get('order'):
            if request.GET.get('order') == 'asc': obj_data = obj_data.order_by(request.GET.get('sort'))
            if request.GET.get('order') == 'desc': obj_data = obj_data.order_by('-' +request.GET.get('sort'))
        if request.GET.get('search') and viewtype =='api': # add additional filter for  api key and also sorting
            if str_search : 
                filter_search =  {str_search + '__icontains':request.GET.get('search')}
                #print(filter_search)
                obj_data = obj_data.filter(**filter_search)
            if request.GET.get('limit') : obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]                
            return JsonResponse(cf_rel_api_fk_fields(obj_model, obj_data,lf_gettbl(obj_data,obj_data.count(), int_recordcount,list_dt=list_dt, list_time= list_time_format)), safe=False)    
        elif request.GET.get('limit')  and viewtype =='api':      
            obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse(cf_rel_api_fk_fields(obj_model, obj_data,lf_gettbl(obj_data,int_recordcount,int_recordcount,list_dt=list_dt)), safe=False)
        elif viewtype =='api':              return JsonResponse(cf_rel_api_fk_fields(obj_model,obj_data,lf_gettbl(obj_data,int_recordcount,int_recordcount,list_dt=list_dt, list_time= list_time)), safe=False)
        elif viewtype =='csv':              return lf_getcsv(obj_data,str_name)
        elif viewtype =='tbl': 
            form1 = form_search(request.GET)
            context = {'jsoncolumn' : lf_get_tbl_clmn(obj_model,list_view), 'tblname': str_name +' List', 'title': str_name + ' List View', 'baseurl': baseurl+'?' +lf_get_filterdic_req(dic_filter), 'editurl': editurl, 'form':form1, 'obj_help' : obj_help, 'patentid' : pid}
            return render(request,'base/tbl_bs_patient.html', context)
        else: return HttpResponseRedirect('/')
    else: return HttpResponseRedirect('/')



def view_tbl_for_desk(request,viewtype ='tbl',*args, **kwargs):
    return view_base_patient_list_desk(request,employee,form_employee_search,form_employee.Meta.fields ,form_employee.Meta.fields, 'Employee',viewtype,'view_employee','employee_name')

@login_required
def view_homepage(request):
    help_id = 'notes_welcome'
    if instruction.objects.filter( uid = help_id).exists(): 
        obj_help = instruction.objects.filter( uid = help_id)[0]
    context = {'obj_help':obj_help,'title': 'Home Page' } 
    return render(request,'base/home.html',context)

@login_required
def view_patient_details(request,pid):    
    if patient.objects.filter(pk = pid).exists():
        if request.method == "POST":      
            photo_base64 = request.POST.get('photodata').replace( 'data:image/png;base64,','').replace(" ", "+")
            imgdata = base64.b64decode(photo_base64)
            str_imgfile = r'static/patient/profile/' + str(pid) + '_photo.jpg'
            with open(str_imgfile, 'wb') as f:    f.write(imgdata)
            patient.objects.filter(pk = pid).update(profile_pic = str_imgfile )
        obj_patient = patient.objects.get(pk = pid)
        help_id = 'view_patient_details'
        if instruction.objects.filter( uid = help_id).exists(): 
            obj_help = instruction.objects.filter( uid = help_id)[0]
        context = {'obj_patient':obj_patient, 'patient_summary': lf_patient_summary(pid), 'obj_help':obj_help, 'patentid' : pid,'title': 'Patient details'} 
        return render(request,'base/patient_details_mobile.html',context)
    return HttpResponseRedirect(reverse('home'))

@login_required
def view_base_patient_list_desk(request,obj_model,form_search, list_filter=[],list_view=[], str_name ='',viewtype ='tbl',help_id='', str_search = ''):
    str_path = request.path
    str_path_parent = str_path.replace(str_path.split('/')[len(str_path.split('/'))-1],'')
    editurl =  reverse('base:patient_details') #str_path_parent + 'form/'
    viewurl = reverse('base:patient_details') 
   # print(viewurl)
    baseurl = str_path_parent + 'api'
    deleteurl = str_path_parent + 'delete/'

    if  request.user.is_authenticated and request.user.is_staff: 
        obj_help =''    #messages.success(request, 'welcome <b>' + request.user.username + '</b>, to Django Development', 'success')
        if instruction.objects.filter( uid = help_id).exists(): 
            obj_help = instruction.objects.filter( uid = help_id)[0]

    #print(str_path_parent)
    if request.method == "GET":
        dic_filter = lf_get_filterdic(request, list_filter)
        obj_data = obj_model.objects.filter(**dic_filter)# one time filter
        int_recordcount = obj_data.count()
        if viewtype =='api' and request.GET.get('order'):
            if request.GET.get('order') == 'asc': obj_data = obj_data.order_by(request.GET.get('sort'))
            if request.GET.get('order') == 'desc': obj_data = obj_data.order_by('-' +request.GET.get('sort'))
        if request.GET.get('search') and viewtype =='api': # add additional filter for  api key and also sorting
            filter_search =  {str_search + '__icontains':request.GET.get('search')}
            obj_data = obj_data.filter(**filter_search)
            if request.GET.get('limit') : obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse(lf_gettbl(obj_data,obj_data.count(), int_recordcount), safe=False)
        
        elif request.GET.get('limit')  and viewtype =='api':      
            obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse(lf_gettbl(obj_data,int_recordcount,int_recordcount), safe=False)
        elif viewtype =='api': return JsonResponse(lf_gettbl(obj_data,int_recordcount,int_recordcount), safe=False)
        elif viewtype =='csv': return lf_getcsv(obj_data,str_name)
        elif viewtype =='tbl': 
            form1 = form_search()#form_search(request.GET)
            context = {'jsoncolumn' : lf_get_tbl_clmn(obj_model,list_view), 'tblname': str_name +' List', 'title': str_name + ' List View', 'baseurl': baseurl+'?' +lf_get_filterdic_req(dic_filter), 'editurl': editurl, 'viewurl': viewurl,'form':form1, 'obj_help' : obj_help}
            return render(request,'base/tbl_view_desk.html', context)
            #return render(request,'baseapp/tbl_bs2_tag.html', context)
        else: return HttpResponseRedirect('/')
    else: return HttpResponseRedirect('/')



@login_required
def view_employee_details(request,eid=0):  
    #print(request.path)
    if request.method == "POST":    
        if employee.objects.filter(str_username = request.user.username).exists():  
            photo_base64 = request.POST.get('photodata').replace( 'data:image/png;base64,','').replace(" ", "+")
            imgdata = base64.b64decode(photo_base64)
            str_imgfile = r'static/employee/profile/' + str(eid) + '_photo.jpg'
            with open(str_imgfile, 'wb') as f:    f.write(imgdata)
            employee.objects.filter(pk = eid).update(profile_pic = str_imgfile )
    if  eid==0: 
        if employee.objects.filter(str_username = request.user.username).exists():              return HttpResponseRedirect(reverse('base:employee_details',   kwargs={'eid': str(employee.objects.filter(str_username = request.user.username)[0].id)}))
        else: 
            messages.error(request,"Employee ID is not assigned for your login", extra_tags='danger') 
            return HttpResponseRedirect(reverse('home'))
    elif employee.objects.filter(pk = eid).exists():
        if instruction.objects.filter( uid = 'view_employee_details').exists():             obj_help = instruction.objects.filter( uid = 'view_employee_details')[0]
        obj_employee = employee.objects.get(pk = eid)
        return render(request,'base/employee_view.html',{'obj_help': obj_help,'obj_employee':obj_employee,'title': 'My details' }   )
    else:
        messages.error(request,'Employee You are looking for is not available please check', extra_tags='danger')
        return HttpResponseRedirect(reverse('home'))

def view_bootnav(request):  
        return render(request,'test/test_nav.html'  )

def view_bootnav_for_patient(request):  
        return render(request,'test/test_nav_patient.html'  )

@login_required
def view_dashboard(request):    return render(request,'baseapp/dashboard_1.html')
@login_required
def view_device(request):    return render(request,'base/base.html')
#def view_mob_width(request):    return render(request,'base/view_mob_width.html')
@login_required
def view_mob_width(request, id = 0):    return formview_base(request,form_patient,patient,'Patient',id)

@login_required
def redirect_after_login(request):
    nxt = request.GET.get("next", None)
   # print(nxt)
    if nxt is None:
        return redirect(settings.LOGIN_REDIRECT_URL)
    elif not url_has_allowed_host_and_scheme(
            url=nxt,
            allowed_hosts={request.get_host()},
            require_https=request.is_secure()):
        return redirect(settings.LOGIN_REDIRECT_URL)
    else:
        return redirect(nxt)

# not login_required 
def view_login(request):        
    #print(get_client_ip(request))
    if request.method == "POST":
        #form_captcha = form_login_captcha(request.POST)
        # if form_captcha.is_valid() == False:
        #     messages.error(request,'Incorrect Captcha, Please Enter correct Captcha details', extra_tags='danger')
        #     return render(request, 'base/login.html')       
        str_username  = request.POST["Username"]
        str_password  = request.POST["password"]
        user = authenticate(request, username=str_username, password=str_password)
        if user is not None:
            if employee.objects.filter(str_username = str_username).exists(): 
                login(request, user)   
                messages.success(request, 'Successfully logged in, Welcome to Ayush')
                return HttpResponseRedirect(reverse('base:home'))
            else:
                messages.error(request,'User Without Employee Details unable to login please connect with System Admin', extra_tags='danger')
                return HttpResponseRedirect(reverse('login'))
            # try: return redirect_after_login(request)
            # except: redirect(reverse('base:home'))
        else:
            #messages.warning(request, 'username password incorrect' + ', username:' + str_username )
            logger.warning('username password incorrect' + ', username:' + str_username )
            messages.error(request,'username or password is incorrect please try again with correct password or connect with siteadmin. This site will allow only autherized persons', extra_tags='danger')
            return render(request, 'base/login.html', {'str_username': str_username})
    # elseinvalid 
    elif request.user.is_authenticated: return HttpResponseRedirect(reverse('base:home'))
    else:
        #form_captcha = form_login_captcha(request.POST)
        return render(request, 'base/login.html')#, {'form': form_captcha})



# @login_required
# def formview_country_state(request, pid=1,id = 0):    return formview_base_patient(request,form_country_state,country_state,'State',pid,id)
@login_required
def deleteview_country_state(request,id = 0):   return view_base_delete(country_state,request,id)
@login_required
def formview_tags(request,pid=1, id = 0):    return formview_base_patient(request,form_tags,tags,pid ,'Tag',id)
@login_required
def deleteview_tags(request,id = 0):   return view_base_delete(tags,request,id)

@login_required
def view_tags(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,tags,form_tags_search, ['tag_name','tag_description','tag_color','id'],['tag_name','tag_description','tag_color','id'],'tags',viewtype) 
#view list for tags
# @login_required
# def view_country_state(request,viewtype ='tbl',*args, **kwargs):
#     return view_base(request,country_state,form_country_state_search, ['countrycode', 'country_name','state_code','state_name','id'],[ 'state_code','state_name','countrycode'],'country_state',viewtype)


@login_required
def view_patient(request,viewtype ='tbl',*args, **kwargs):
    list_view = ["profile_pic",        "Title",
        "Patient_name",        "last_name",
        "fk_gender",        "DoB",
        "Address1",        "locality",
        "city",        "Pincode",
        "fk_dist",        "proof",
        'proof_number',        "email",
        "phone_number",        "alt_phone_number",        "fk_zone"]
    return view_base_patient_list(request,patient,form_patient_search,list_view,list_view,'Patient',viewtype,'view_patient','Patient_name')

@login_required
def formview_patient(request, id = 0):    
    #return formview_base(request,form_patient,patient,'Patient',id,'add_patient')
    obj_form = form_patient;  obj_inst = patient; obj_name = 'Patient'
    help_id= 'add_patient'
    if  request.user.is_authenticated and request.user.is_staff: 
        if employee.objects.filter(str_username = request.user.username).exists(): obj_emp = employee.objects.filter( str_username = request.user.username)[0]
        obj_help =''    
        if instruction.objects.filter( uid = help_id).exists():             obj_help = instruction.objects.filter( uid = help_id)[0]
        context = {'title': 'Add New ' + obj_name +' details','obj_help':obj_help}     
        if  request.method == "GET": 
            if id == 0 : # if there is a new form need to be updated
                form = obj_form() ; context['form'] = form
                messages.info(request, 'New Form, Please enter your delails')
            
            elif obj_inst.objects.filter(id=id).exists() == False: return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))# if the data is not available
            else: # edit an entry
                form =  obj_form(instance= obj_inst.objects.get(id=id))
                messages.warning(request, 'Edit Form, Please Check details properly before submit')
                context = {'title': 'Edit ' + obj_name +' details - ' + obj_inst.objects.get(id=id).__str__(), 'form':form, 'obj_help':obj_help }
        elif request.method == "POST":
           if id == 0 : form = obj_form(request.POST or None,request.FILES)  # if there in a new  form
           else: form = obj_form(request.POST or None,request.FILES,instance= obj_inst.objects.get(id=id))  # for editing instance shuold be added
           if form.is_valid():
              if id == 0 : # for new entry 
                    try:  # if entry has employee field
                        dic_formdata = form.cleaned_data
                        dic_formdata['fk_employee'] = obj_emp
                        #print(dic_formdata)
                        #obj_inst.objects.create(**form.cleaned_data, fk_employee = obj_emp) 
                        obj_patient =    obj_inst.objects.create(**dic_formdata, fk_zone = obj_emp.fk_zone )
                        #messages.success(request, "Your Entry has been updated")
                        form = obj_form() 
                        return HttpResponseRedirect(reverse('base:patient_details',  kwargs={'pid':obj_patient.id} ))
                    except Exception as err: messages.error(request, str(err), 'danger')  
                    context = {'title': 'Add New ' + obj_name +' details', 'form':form,'obj_help':obj_help }
              else :  # for edit
                  form.save();                  messages.success(request, "Profile details updated.")
                  return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))
           else: 
               context['form'] = form;context['title'] =  obj_name +' Errors in form: please check details';  messages.error(request, form.errors, 'danger')
        return render(request, "base/view_form.html", context)  
    else:
        return redirect("/") 


@login_required
def deleteview_patient(request,id = 0):   return view_base_delete(patient,request,id)


@login_required
def employee_disable(request, id = 0):    #return formview_base(request,form_employee,employee, 'Employee',id,'add_employee')
    if  request.user.is_authenticated and request.user.is_staff and employee.objects.filter(str_username = request.user.username).exists(): 
        if employee.objects.filter(pk = id).exists(): 
            if User.objects.filter(username = employee.objects.get(pk = id).str_username).exists():
               obj_user =  User.objects.get(username = employee.objects.get(pk = id).str_username)
               obj_user.is_active = False
               obj_user.is_staff = False
               obj_user.save()
               messages.warning(request, 'User Name: ' + obj_user.username + '<br> has been disabled.', 'danger')
               return HttpResponseRedirect(reverse('siteadmin:employee'))
            else: return(reverse('home'))
        else: return(reverse('home'))    
    else: return(reverse('home'))

def employee_enable(request, id = 0):    #return formview_base(request,form_employee,employee, 'Employee',id,'add_employee')
    if  request.user.is_authenticated and request.user.is_staff and employee.objects.filter(str_username = request.user.username).exists(): 
        if employee.objects.filter(pk = id).exists(): 
            if User.objects.filter(username = employee.objects.get(pk = id).str_username).exists():
               obj_user =  User.objects.get(username = employee.objects.get(pk = id).str_username)
               obj_user.is_active = True
               obj_user.is_staff = True
               obj_user.save()
               messages.success(request, 'User Name: ' + obj_user.username + '<br> has been enabled.')
               return HttpResponseRedirect(reverse('siteadmin:employee'))
            else: return(reverse('home'))
        else: return(reverse('home'))    
    else: return(reverse('home'))



@login_required
def formview_employee(request, id = 0):    #return formview_base(request,form_employee,employee, 'Employee',id,'add_employee')
    obj_form = form_employee;  obj_inst = employee; obj_name = 'Employee'
    help_id= 'add_employee'
    if  request.user.is_authenticated and request.user.is_staff: 
        if employee.objects.filter(str_username = request.user.username).exists(): obj_emp = employee.objects.filter( str_username = request.user.username)[0]
        obj_help =''    
        if instruction.objects.filter( uid = help_id).exists():             obj_help = instruction.objects.filter( uid = help_id)[0]
        context = {'title': 'Add New ' + obj_name +' details','obj_help':obj_help}  
        if  request.method == "GET": 
            if id == 0 : # if there is a new form need to be updated
                form = obj_form() ; context['form'] = form
                messages.info(request, 'New Form, Please enter your delails')

            elif obj_inst.objects.filter(id=id).exists() == False: return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))# if the data is not available
            else: # edit an entry
                form =  obj_form(instance= obj_inst.objects.get(id=id))
                messages.warning(request, 'Edit Form, Please Check details properly before submit')
                context = {'title': 'Edit ' + obj_name +' details - ' + obj_inst.objects.get(id=id).__str__(), 'form':form, 'obj_help' : obj_help }
        elif request.method == "POST":
           if id == 0 : form = obj_form(request.POST or None)  # if there in a new  form
           else: form = obj_form(request.POST or None,instance= obj_inst.objects.get(id=id))  # for editing instance shuold be added
           if form.is_valid():
              if id == 0 : # for new entry 
                  try:  # if entry has employee field
                      str_newpass = localfunc.get_password(8)
                      myuser = User.objects.create_user(request.POST.get("str_username", False), request.POST.get("email", False),str_newpass)
                      myuser.is_staff = True
                      myuser.save()    
                      #print(form.cleaned_data)
                      obj_inst.objects.create(**form.cleaned_data)                   
                      messages.success(request, "Employee login details <br> username: "  + request.POST.get("str_username", False) + '<br>password: '+ str_newpass )
                      form = obj_form() 
                  except Exception as err: 
                      messages.error(request, str(err), 'danger')  
                      messages.error(request, 'Employee details not created', 'danger')  
                  context = {'title': 'Add New ' + obj_name +' details', 'form':form , 'obj_help' : obj_help}
              else :  # for edit
                  form.save();                  messages.success(request, "Profile details updated.")
                  return HttpResponseRedirect(request.path.replace('/form/'+str(id),'/tbl'))
           else: 
               context['form'] = form;context['title'] =  obj_name +' Errors in form: please check details';  messages.error(request, form.errors, 'danger')
        return render(request, "base/view_form.html", context)  
    else:
        return redirect("/") 

@login_required
def view_employee(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,employee,form_employee_search,form_employee.Meta.fields ,form_employee.Meta.fields,'Employee',viewtype,'employee_name','view_employee')



@login_required
def formview_disease(request,pid=1, id = 0):    return formview_base(request,form_disease,disease,'Disease',id,'add_disease')

@login_required
def view_disease(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,disease,form_disease_search,form_disease.Meta.fields ,form_disease.Meta.fields,'Disease',viewtype,'disease_name','view_disease')

#(obj_model,form_search, request,list_filter=[],list_view=[], str_name ='',viewtype ='tbl')

@login_required
def formview_task(request, id = 0):    return formview_base(request,form_task,task,'Task',id,'add_task')

@login_required
def view_task(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,task,form_task_search,form_task.Meta.fields ,form_task.Meta.fields,'Task',viewtype,'task_type','view_task')
# ['task_type','task_details','fk_employee']


@login_required
def formview_treatment(request,pid=1, id = 0):    return formview_base_patient(request,form_treatment,treatment,'Treatment',pid,id,'add_treatment')

@login_required
def view_treatment(request,viewtype ='tbl',*args, **kwargs):
    return view_base_patient_list(request,treatment,form_treatment_search,form_treatment.Meta.fields ,form_treatment.Meta.fields,'Treatment',viewtype,'treatment_name','view_treatment')


@login_required
def formview_zone(request, id = 0):    return formview_base(request,form_zone,Zone,'Zone',id,'add_zone')

@login_required
def view_zone(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,Zone,form_zone_search,form_zone.Meta.fields ,form_zone.Meta.fields,'Zone',viewtype,'center','view_zone')


@login_required
def formview_gender(request, id = 0):    return formview_base(request,form_gender,gender,'Gender',id,'add_gender')

@login_required
def view_gender(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,gender,form_gender_search,form_gender.Meta.fields ,form_gender.Meta.fields,'Gender',viewtype,'gender_name','view_gender')


@login_required
def formview_Master_GST(request, id = 0):    return formview_base(request,form_Master_GST,Master_GST,'GST',id,'add_gst')

@login_required
def view_Master_GST(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,Master_GST,form_Master_GST_search,form_Master_GST.Meta.fields ,form_Master_GST.Meta.fields,'GST',viewtype,'gst_shorttext','view_gst')



@login_required
def formview_District_State(request, id = 0):    return formview_base(request,form_District_State,District_State,'District & State',id,'add_district')

@login_required
def view_District_State(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,District_State,form_District_State_search,form_District_State.Meta.fields ,form_District_State.Meta.fields,'District & State',viewtype,'District','view_district')



@login_required
def formview_Zone_System(request, id = 0):    return formview_base(request,form_Zone_System,Zone_System,'Zone System',id,'add_zone_system')

@login_required
def view_Zone_System(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,Zone_System,form_Zone_System_search,form_Zone_System.Meta.fields ,form_Zone_System.Meta.fields,'Zone System',viewtype,'System','View_zone_system')


@login_required
def formview_Zone_Type(request, id = 0):    return formview_base(request,form_Zone_Type,Zone_Type,'Zone Type',id,'add_zone_type')

@login_required
def view_Zone_Type(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,Zone_Type,form_Zone_Type_search,form_Zone_Type.Meta.fields ,form_Zone_Type.Meta.fields,'Zone Type',viewtype,'Ztype','view_zone_type')

@login_required
def formview_ID_type(request, id = 0):    return formview_base(request,form_ID_type,ID_type,'ID Type',id,'add_id')

@login_required
def view_ID_type(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,ID_type,form_ID_type_search,form_ID_type.Meta.fields ,form_ID_type.Meta.fields,'ID Type',viewtype,'name','view_id')

@login_required
def formview_User_Group(request, id = 0):    return formview_base(request,form_User_Group,User_Group,'User Group',id,'add_User_Group')
@login_required
def view_User_Group(request,viewtype ='tbl',*args, **kwargs):
    return view_base(request,User_Group,form_User_Group_search,form_User_Group.Meta.fields ,form_User_Group.Meta.fields,'User Group',viewtype,'name','view_User_Group')


# temproary views 
def update_inital_view(request):
    initalconfig.update_initial_disease()


def get_db_models(request):    return initalrun.get_db_model_details_main()
def update_inital_view2(request):    return HttpResponse('Process Completed. Please find below details.\n' + initalrun.update_datasets_models())
def html_backup(request):    return HttpResponse('Process Completed. Please find below details.\n' + initalrun.get_HTML_Backup())
def html_update(request):    return HttpResponse('Process Completed. Please find below details.\n' + initalrun.get_HTML_update())
def html_photo_test(request):  
    print(request.POST )
    return render(request, 'test/photo.html')
#
def view_test_report(request):    
    return JsonResponse(base_reports.get_disease_report_main(), safe=False)

def view_testjson(request):
    dataJSON  = json.dumps(base_reports.get_disease_report_main()['table'])
    return render(request, 'test/testjsonjs.html', {'output': dataJSON} )





def lf_tuples_to_dictionary(list_tuple):
    dict_data = {}
    for tuple_data in  list(list_tuple.lists()): dict_data[tuple_data[0]] = tuple_data[1]
    return dict_data

def lf_report_getquery(dic_filter):
    obj_query =  lf_tuples_to_dictionary(dic_filter)
    str_group = ''
    #tuple_data = list(dic_filter.lists())
    #if tuple_data!= []:
    if 'district'  in obj_query.keys() : 
        for str_key in obj_query['district']: str_group += 'district=' + str_key+'&' 
    if 'zone' in obj_query.keys(): 
        for str_key in obj_query['zone']:str_group += 'zone=' + str_key+'&' 
    if 'report_period' in obj_query.keys():  
        for str_key in obj_query['report_period']:str_group += 'report_period=' + str_key+'&' 
    if 'submit'  in obj_query.keys() :  
        for str_key in obj_query['submit']:str_group += 'submit=' + str_key+'&'      
    if 'emplyid'  in obj_query.keys() :  
        for str_key in obj_query['emplyid']:str_group += 'emplyid=' + str_key+'&'           
    return str_group

def view_dynamic_report(request, viewtype ='tbl'):
    str_path = request.path
    str_path_parent = str_path.replace(str_path.split('/')[len(str_path.split('/'))-1],'')
    baseurl = str_path_parent + 'api'
    help_id='view_report_IMH'
    if request.method == "GET": 
        if instruction.objects.filter( uid = help_id).exists():             obj_help = instruction.objects.filter( uid = help_id)[0]
        else: obj_help =''        
        dic_qeury = lf_tuples_to_dictionary(request.GET)
        report_data = base_reports.get_disease_IMH_report_main(request,dic_qeury) #base_reports.get_disease_report_main( )  
        if viewtype =='tbl':
            if  len(dic_qeury) ==0 :    form1 = form_report_base()         # if there is no query data
            else:                       form1 = form_report_base(request.GET)# post submit of search form
        if viewtype =='api':         return JsonResponse( report_data, safe=False)# if API or report
        return render(request, 'report/disease_IMH.html', {'report_data': report_data,'title': 'IMH Report', 'form': form1, 'str_querypath':baseurl+'?' +lf_report_getquery(request.GET) ,'obj_help' : obj_help})#.update({'report_type': 'State Level'}) )
    else: return HttpResponseRedirect(reverse('home'))

# test views 
def view_testdashboard(request):
    help_id = 'notes_welcome'
    if instruction.objects.filter( uid = help_id).exists(): 
        obj_help = instruction.objects.filter( uid = help_id)[0]
    context = {'obj_help':obj_help} 
    return render(request,'test/disease.html',context)    





@login_required
def view_report_IMH(request,obj_model,form_search, list_filter=[],list_view=[], str_name ='',viewtype ='tbl', str_search = '',help_id=''):
    str_path = request.path
    str_path_parent = str_path.replace(str_path.split('/')[len(str_path.split('/'))-1],'')
    editurl = str_path_parent + 'form/'
    baseurl = str_path_parent + 'api'
    deleteurl = str_path_parent + 'delete/'

    if  request.user.is_authenticated and request.user.is_staff: 
        if instruction.objects.filter( uid = help_id).exists():             obj_help = instruction.objects.filter( uid = help_id)[0]
        else: obj_help =''
    if request.method == "GET":
        dic_filter = lf_get_filterdic(request, list_filter)
        obj_data = obj_model.objects.filter(**dic_filter)# one time filter
        obj_data  = obj_data.order_by('-id')
        int_recordcount = obj_data.count()
        if viewtype =='api' and request.GET.get('order'):
            if request.GET.get('order') == 'asc': obj_data = obj_data.order_by(request.GET.get('sort'))
            if request.GET.get('order') == 'desc': obj_data = obj_data.order_by('-' +request.GET.get('sort'))
        if request.GET.get('search') and viewtype =='api': # add additional filter for  api key and also sorting
            filter_search =  {str_search + '__icontains':request.GET.get('search')}
            obj_data = obj_data.filter(**filter_search)
            if request.GET.get('limit') : obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse( lf_gettbl(obj_data,obj_data.count(), int_recordcount), safe=False)
        elif request.GET.get('limit')  and viewtype =='api':      
            obj_data = obj_data[int(request.GET.get('offset')) :int(request.GET.get('limit'))+int(request.GET.get('offset'))]
            return JsonResponse(lf_gettbl(obj_data,int_recordcount,int_recordcount), safe=False)
        elif viewtype =='api': 
            return JsonResponse(lf_gettbl(obj_data,int_recordcount,int_recordcount), safe=False)
        elif viewtype =='csv': return lf_getcsv(obj_data,str_name)
        elif viewtype =='tbl': 
            form1 = form_search(request.GET)
            context = {'jsoncolumn' : lf_get_tbl_clmn(obj_model,list_view), 'tblname': str_name +' List', 'title': str_name + ' List', 'baseurl': baseurl+'?' +lf_get_filterdic_req(dic_filter), 'editurl': editurl, 'form':form1, 'obj_help' : obj_help}
            return render(request,'base/tbl_bs.html', context)
        else: return HttpResponseRedirect('/')
    else: return HttpResponseRedirect('/')

from .internal import  initalrun
def test_inital_upload(request):
    initalrun.update_inital_data()
    return HttpResponseRedirect('/')






def test_performance_dboard(request, viewtype ='tbl'):
    str_path = request.path
    str_path_parent = str_path.replace(str_path.split('/')[len(str_path.split('/'))-1],'')
    baseurl = str_path_parent + 'api'
#1130   
    if request.method == "GET": 
        help_id='view_report_performance' 
        if instruction.objects.filter( uid = help_id).exists():             obj_help = instruction.objects.filter( uid = help_id)[0]
        else: obj_help =''  
        dic_qeury = lf_tuples_to_dictionary(request.GET)
        report_data = base_reports.employee_perfomance(request, dic_qeury)
        if viewtype =='tbl':
            if  len(dic_qeury) ==0 :    form1 = form_report_employ()         # if there is no query data
            else:                       form1 = form_report_employ(request.GET)# post submit of search form
            return render(request, 'report/perfomance.html', {'report_data': report_data,'title': 'Center Performance', 'form': form1, 'str_querypath':baseurl+'?' +lf_report_getquery(request.GET),'obj_help':obj_help })#.update({'report_type': 'State Level'}) )
        if viewtype =='api':         return JsonResponse( report_data, safe=False)# if API or report
        
    else: return HttpResponseRedirect(reverse('home'))
    




def view_stock_overview(request,  viewtype ='tbl'):
    # list stock and show by product group wise
    str_path = request.path
    str_path_parent = str_path.replace(str_path.split('/')[len(str_path.split('/'))-1],'')
    baseurl = str_path_parent + 'api'
    if request.method == "GET":  
        dic_qeury = lf_tuples_to_dictionary(request.GET)
        if viewtype =='tbl':
            help_id='view_report_stock_movement'   
            if  len(dic_qeury) ==0 :    form1 = form_report_base() # if there is no query data
            else:                       form1 = form_report_base(request.GET)# post submit of search form
        if viewtype =='tbl2':
            help_id='view_report_stock_availability'   
            if  len(dic_qeury) ==0 :    form1 = form_report_stock_check() # if there is no query data
            else:                       form1 = form_report_stock_check(request.GET)# post submit of search form            
        if viewtype =='tbl' or viewtype =='tbl2':    
            if instruction.objects.filter( uid = help_id).exists():             obj_help = instruction.objects.filter( uid = help_id)[0]
            else: obj_help =''              
            list_tbl_header =  [{ 'header': 'fk_med__id', 'title': 'ID'}, { 'header': 'fk_med__drug_name', 'title': 'Drug Name'},{ 'header': 'fk_med__drug_tamil', 'title': 'In Tamil'},{ 'header': 'fk_med__fk_system__System', 'title': 'System'},{ 'header': 'fk_med__packaging', 'title': 'Packaging'},   { 'header': 'TotalEntry', 'title': 'Total Entry'},{ 'header': 'Available', 'title': 'Available'}]
            report_data = base_reports.stock_review(request, dic_qeury, viewtype)
            return render(request, 'report/stock.html', {'report_data': report_data, 'list_tbl_header':list_tbl_header,'title': 'Stock Check', 'form': form1, 'str_querypath':baseurl+'?' +lf_report_getquery(request.GET), 'obj_help': obj_help })#.update({'report_type': 'State Level'}) )
        if viewtype =='api':         return JsonResponse( base_reports.stock_review_api(request, dic_qeury), safe=False)# if API or report
        else: return HttpResponseRedirect(reverse('home'))
        #return render(request, 'report/perfomance.html', {'report_data': report_data,'title': 'Center Performance', 'form': form1, 'str_querypath':baseurl+'?' +lf_report_getquery(request.GET) })#.update({'report_type': 'State Level'}) )
    else: return HttpResponseRedirect(reverse('home'))