from datetime import datetime
from baseapp.models import  patient,employee,disease,task,treatment,gender,ID_type, User_Group, Master_GST, Master_captcha, Zone_System, Zone_Type,Zone, District_State
from help.models import instruction,static_page,notification
from diagnoses.models import diagnose,condition,disease_details
from consult.models import observation,nutritional_value,blood_Pressure,History_examination,vitals,scheduling,treatment_details
from medic.models import medications,medic_inhouse,inventory_entry
from django.urls import reverse
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from datetime import datetime as dt
from baseapp  import views as base_views
from django.db import migrations, models
import os, openpyxl, json, csv, webbrowser
from pathlib import Path
from . import localfunc
from subprocess import check_output 

dic_map = {} 
list_model_base = [gender, Zone_Type, Zone_System, District_State, Zone, User_Group,ID_type, employee,  
               Master_GST,  disease, patient, treatment,medic_inhouse]
list_model_HTML = [ task, instruction, static_page, notification]
list_model_patients = [diagnose, condition, disease_details, observation, nutritional_value, blood_Pressure, History_examination, vitals, treatment_details,
medications, inventory_entry]
list_models = list_model_base + list_model_HTML + list_model_patients



 # HTML 

# Global Variables
BASE_DIR = Path(__file__).parent.parent 
str_fileloc = os.path.join(BASE_DIR, 'data', 'upload', 'Master_file.xlsx')
str_file_sdd = os.path.join(BASE_DIR, 'data', 'test', 'sdd.xlsx')

#print(str(str_fileloc))
wb_input = openpyxl.load_workbook(str_fileloc)


def update_input(obj_model, str_field, str_default):
     for obj_field in obj_model._meta.fields: 
        if obj_field.name == str_field: 
             #print(obj_field.get_internal_type(), str_field ) 
             
             if str_field[0:2] == 'fk'       :               return obj_field.related_model.objects.all()[0] 
             if str_field[0:8] == 'applyto_' :               return obj_field.related_model.objects.all()[0] 
             if str(obj_field.get_internal_type())  == 'DateTimeField':                 return datetime.strptime(str_default, '%Y-%m-%d %H:%M:%S')
             if str_default is None and str(obj_field.get_internal_type())  == 'CharField': return ''
             else: return str_default

def get_HTML_Backup():
    # this function will create the backup of HTML files with model_ID_field as html file in  folder
    for obj_model in list_model_HTML:
        for obJ_entry in obj_model.objects.all():
            for obj_field in obj_model._meta.fields: 
                str_field = type(obj_field).__name__ 
                if str_field ==  'RichTextField': 
                    str_filename = str(obj_model.__name__) +  '_' + str(obJ_entry.id) + '_' + obj_field.name + '.html'
                    str_fileloc = os.path.join(BASE_DIR, 'data', 'backup', str_filename)
                    obj_file = open(str_fileloc, 'w', encoding="utf-8")
                    #print(obj_field.name)
                    if obJ_entry.__dict__[obj_field.name] is not None: 
                        obj_file.write(obJ_entry.__dict__[obj_field.name])
                    obj_file.close()
    return 'Please check folder' + os.path.join(BASE_DIR, 'data', 'backup')


def get_HTML_update():
    # this function will create the backup of HTML files with model_ID_field as html file in  folder
    for obj_help in instruction.objects.all():
        obj_help.content_HTML = obj_help.content_HTML.replace('_x000D_','')
        obj_help.save()
    #----------------   DON'T DELETE THIS IS WORKING CODE with different logic   --------------------------------
    # for obj_model in list_model_HTML:
    #     for obJ_entry in obj_model.objects.all():
    #         for obj_field in obj_model._meta.fields: 
    #             str_field = type(obj_field).__name__ 
    #             if str_field ==  'RichTextField': 
    #                 #print(obj_field.name)
    #                 str_filename = str(obj_model.__name__) +  '_' + str(obJ_entry.id) + '_' + obj_field.name + '.html'
    #                 str_fileloc = os.path.join(BASE_DIR, 'data', 'backup', str_filename)
    #                 obj_file = open(str_fileloc, 'r', encoding="utf-8")
    #                 if obJ_entry.__dict__[obj_field.name] is not None: 
    #                     obj_model.objects.filter(pk = obJ_entry.id).update(**{obj_field.name : obj_file.read()})
    #                 obj_file.close()
    return 'backup has been update successfully.' 


def update_input_v2(obj_model, str_field, str_default, dic_map):
     for obj_field in obj_model._meta.fields: 
        if obj_field.name == str_field: 
             if obj_field.is_relation :                  
                 str_fk_model = obj_field.related_model.__name__
                 if str_default is None : return obj_field.related_model.objects.all()[0] 
                 return obj_field.related_model.objects.filter(**{ dic_map[str_fk_model]:str_default })[0] 

             if str(obj_field.get_internal_type())  == 'DateTimeField':                 return datetime.strptime(str_default, '%Y-%m-%d %H:%M:%S')
             if str_default is None and str(obj_field.get_internal_type())  == 'CharField': return ''
             else: return str_default

def get_fk_fields():
    ws_data = wb_input['Ref']
    for rownum in range(3,ws_data.max_row + 1):        dic_map[ws_data.cell(row=rownum, column=4).value]=  ws_data.cell(row=rownum, column=5).value
    return dic_map


def update_datasets_models():
    dic_map =    get_fk_fields()
    str_status = ''
    for obj_model in list_models:    
        ws_data = wb_input[str(obj_model.__name__).strip() ]
        for rownum in range(2,ws_data.max_row + 1):
            dic_data = {}
            i = 1
            if ws_data.cell(row=rownum, column=1).value == None: break
            while None != ws_data.cell(row=1, column=i).value and 'id' != ws_data.cell(row=1, column=i).value :   
                
                name1 = ws_data.cell(row=1, column=i).value
                dic_data[name1] =    update_input_v2(obj_model, name1, ws_data.cell(row=rownum, column=i).value, dic_map)  
                i = i + 1     
            obj_mod_created = obj_model.objects.create(**dic_data)
            ws_data.cell(row=rownum, column=i ).value =  obj_mod_created.id
        ws_data.cell(row=1, column=i ).value =  'id'
        print(str(obj_model.__name__).strip()  +  ' - Completed') 
        str_status = str_status +   str(obj_model.__name__).strip()  +  ' - Completed. \n'  
    return str_status
        



def get_db_model_details_main():
    response = HttpResponse(content_type='text/csv', #.values()) # default unfiltered 
    headers={'Content-Disposition':'attachment; filename="'+  'db_model_details_' + dt.now().strftime("%d-%m-%y_%H-%M") + '.csv"'}, )
    writer = csv.writer(response)
    # Headers 
    writer.writerow(('Application', 'Model', 'verbose_name', 'verbose_name_plural' , 'Field Name','Field Type','Field Verbose Name', 'help_text' , 'Default Value' ,'str_related_model','is_relation', 'max_length'))
    
    str_mod_vname = ''
    str_mod_vpname =''
    for obj_model in list_models:
        str_app = obj_model.__module__
        str_model = obj_model._meta.model_name
        str_mod_vname =   obj_model._meta.verbose_name
        str_mod_vpname =   obj_model._meta.verbose_name_plural
        for obj_field in obj_model._meta.fields: 
            str_name =  obj_field.name
            str_type =  obj_field.__class__.__name__
            str_verbose_name =  obj_field.verbose_name
            obj_field.help_text
            is_relation  = obj_field.is_relation
            
            if obj_field.is_relation:                str_related_model  =  obj_field.related_model.__name__ 
            else: str_related_model = '' # default value 
            writer.writerow((str_app, str_model,  str_mod_vname, str_mod_vpname,  str_name,str_type,str_verbose_name, obj_field.help_text,obj_field.__dict__['default'],str_related_model, is_relation,obj_field.__dict__['max_length'],obj_field.__dict__['blank'],obj_field.__dict__['null']))
    return response
        

def get_db_model_genAI(request, appname):
    global str_file_sdd
    #print(request.__dict__['environ']['HTTP_HOST'])
    #str_url = 'http://192.168.0.153:8085/admin/'+  str_app.replace('.models','/') + str_model + '/export/'
    #str_status += '<br>URL Opened completed: ' +  str_url
    response = HttpResponse(content_type='text/txt', #.values()) # default unfiltered 
                            headers={'Content-Disposition':'attachment; filename="'+  'custom_module' + appname + '.py"'}, )
    # response = HttpResponse(content_type='application/liquid; charset=utf-8', #.values()) # default unfiltered 
    #                         headers={'Content-Disposition':'attachment; filename="'+  'custom_module' + appname + '.py"'}, )    
    
    writer = csv.writer(response,delimiter=";",escapechar=" ")
    # Headers 
    writer.writerow(('from django.db import models',))
    writer.writerow(('from datetime import datetime',))
    writer.writerow(('from ckeditor.fields import RichTextField',))
    writer.writerow(('from colorfield.fields import ColorField',))
    writer.writerow(('from django.utils import timezone',))
    writer.writerow(("from django.db.models.signals import pre_save, post_save",))
                
    writer.writerow(('# This Model file is Auto generated by site',))
    # starts from Model Name
    wb_input = openpyxl.load_workbook(str_file_sdd) 
    ws_data = wb_input['models'] 
    for rownum in range(2,ws_data.max_row + 1): 
        if ws_data.cell(row=rownum, column=1).value ==    appname:
            str_model = ws_data.cell(row=rownum, column=2).value
            #print(str_model)
            str_verbose = "          verbose_name = '"  + ws_data.cell(row=rownum, column=3).value + "'"
            str_verbose_plural = "          verbose_name_plural = '"  + ws_data.cell(row=rownum, column=4).value + "'"
            writer.writerow(('class '  +  str_model + '(models.Model):',))
            writer.writerow(('      '  +  'class Meta:',))
            writer.writerow((str_verbose,))
            writer.writerow((str_verbose_plural,))
            ws_data2 = wb_input['fields'] 
            for rownum in range(2,ws_data2.max_row + 1): 
                if ws_data2.cell(row=rownum, column=1).value ==    str_model:
                    str_field = "      " + ws_data2.cell(row=rownum, column=2).value  + " = models." + ws_data2.cell(row=rownum, column=3).value + "(" 
                    if ws_data2.cell(row=rownum, column=8).value: str_field += ws_data2.cell(row=rownum, column=8).value + ","
                    str_field += "verbose_name='" + ws_data2.cell(row=rownum, column=4).value + "',"
                    if ws_data2.cell(row=rownum, column=5).value: str_field += "help_text='" + ws_data2.cell(row=rownum, column=5).value + "',"
                    if ws_data2.cell(row=rownum, column=6).value: str_field +=  "default='" + ws_data2.cell(row=rownum, column=6).value + "',"
                    if ws_data2.cell(row=rownum, column=9).value: str_field +=  "max_length=" + str(ws_data2.cell(row=rownum, column=9).value) + ","
                    
                    str_field += ")"
                    writer.writerow((str_field ,))
                    
    
    return response
def get_db_model_genAI_main(request): 
    wb_input = openpyxl.load_workbook(str_file_sdd) 
    ws_data = wb_input['app']
    str_status = ''
    for rownum in range(2,ws_data.max_row + 1):  
        str_app =  ws_data.cell(row=rownum, column=1).value
        str_url = r'http://' + request.__dict__['environ']['HTTP_HOST'] +  reverse('stageenv:gen_script_model',  kwargs={'appname':str_app}  )
        str_status += '<br>URL Opened completed: ' +  str_url
        webbrowser.open(str_url, new=0, autoraise=True)
    return str_status



def export_all_models():
    str_status = ''
    for obj_model in list_models:
        str_app = obj_model.__module__
        str_model = obj_model._meta.model_name
        str_url = 'http://192.168.0.153:8085/admin/'+  str_app.replace('.models','/') + str_model + '/export/'
        str_status += '<br>URL Opened completed: ' +  str_url
        webbrowser.open(str_url, new=0, autoraise=True)
    return str_status
    #'http://192.168.0.153:8085/admin/baseapp/district_state/export/


     
def update_inital_modeldata(obj_model):
    ws_data = wb_input[str(obj_model.__name__).strip() ]
    for rownum in range(2,ws_data.max_row + 1):
        dic_data = {}
        i = 1
        if ws_data.cell(row=rownum, column=1).value == None: break
        while None != ws_data.cell(row=1, column=i).value and 'id' != ws_data.cell(row=1, column=i).value :   
            
            name1 = ws_data.cell(row=1, column=i).value
            dic_data[name1] =    update_input(obj_model, name1, ws_data.cell(row=rownum, column=i).value)  
            i = i + 1     
        obj_mod_created = obj_model.objects.create(**dic_data)
        ws_data.cell(row=rownum, column=i ).value =  obj_mod_created.id
    ws_data.cell(row=1, column=i ).value =  'id'
    print(str(obj_model.__name__).strip()  +  ' - Completed')


    # os.open(str(str_fileloc),)
def update_inital_data():    
    for obj_model in list_models:   update_inital_modeldata(obj_model)       



def create_captchas():
    # Create captcha and save 
    for rownum in range(2,195): 
        print(rownum)
        if  Master_captcha.objects.filter().exists() == False:  
            obj_captcha =  Master_captcha.objects.create(intext = '', )
            localfunc.get_random_number(5)
       # wb_input.save(str(str_fileloc)) # save the file
        #check_output(str_fileloc, shell=True).decode() # open the file    
#update_datasets_models()