from django.shortcuts import render, redirect
from patient.models import *
from Account.models import UserProfile
from .models import doctorRequestsTable
from datetime import date
from django.http.response import HttpResponseRedirect
from datetime import datetime as dt

# Create your views here.


def index(request):
    d=Doctor.objects.get(name=request.user)
    patients=patientGrantTable.objects.filter(docid=d.did).select_related('pid')
    print(patients)
    
    context1={
        'data' : patients,
    }
    return render(request, "doctor_home.html",context1)

def login(request):
    return render(request, "login.html")

def saveprescription(request,patient):
    p=Patient.objects.get(pid=patient)
    d=Doctor.objects.get(name=request.user)
    #print("In saveprescription",d.did,p.pid)
    obj1=Prescription(pid=p,did=d,date=date.today())
    obj1.save()
    medicine=Medication.objects.all()
    context2={
        'data':medicine,
        'patient': patient,
        'prescript':obj1.prescript_id,
    }
    return render(request,"doctor_addprescription.html",context2)

def saveprescriptionmedicine(request):

    medicine=str(request.POST.get('medicine'))
    dose=request.POST.get('dose')
    day=request.POST.get('day')

    presid=request.POST.get('prescriptid')
    print(medicine,dose,day,presid)

    prescription_id=Prescription.objects.get(prescript_id=presid)
    medicine_id=Medication.objects.get(name=medicine)
    print(prescription_id)
    print(medicine_id)
    obj=Prescriptmed(prescript_id=prescription_id,medid=medicine_id,description=dose,days=day)
    obj.save()

    return HttpResponseRedirect("doctorhome")
    
def logout(request):
	return redirect("http://localhost:8000")

def doctorRequest(request):
    if request.method == 'POST':
        pid = request.POST["patientid"]
        did = Doctor.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).did
        pat = Patient(pid=pid)
        dat = Doctor(did=did)
        if pid == "": #  patient ID should not be empty
            print("NULL")
        elif doctorRequestsTable.objects.filter(pid=pat, docid=dat).exists():
            print("Exists")
        else:
            temp = doctorRequestsTable.objects.create(pid=pat, docid=dat)
            temp.save()
        return render(request, "doctorRequest.html")
    else:
        return render(request, "doctorRequest.html")

def doctorshowhisttory(request,patientid):
    print(patientid)
    p=Patient.objects.get(pid=patientid)

    prescriptions=[]
    prescriptmeds=[]
    cbc = []
    meta = []
    mri = []
    xray = []	
	
    if(request.user.is_authenticated and UserProfile.objects.get(user=request.user).profile_type=='Doctor'):
	    date1=None
	    date2=None

	    if request.POST.get("date1") is None or request.POST.get("date2") is None or request.POST["date1"]=='' or request.POST["date2"]=='':
		    date1=None
		    date2=None

	    elif request.method == 'POST':
		    date1 = dt.strptime(request.POST["date1"],"%Y-%m-%d").date()
		    date2 = dt.strptime(request.POST["date2"],"%Y-%m-%d").date()
	
		#Use this to avoid errors while accessing Patient object
    prescriptions = Prescription.objects.select_related('pid','did').filter(pid=p.pid)
    prescriptmeds = Prescriptmed.objects.all().select_related('prescript_id','medid')
    cbc = Commonbloodcount.objects.filter(pid=p.pid)
    meta = Basicmetabolismpanel.objects.filter(pid=p.pid)
    mri = Mri.objects.filter(pid=p.pid)
    xray = Xray.objects.filter(pid=p.pid)
    #patient_name = Patient.objects.get(profile_id=p.id).name # append this in *_table lists if you want patient_name in every tuple 

    cbc_table = []
    for pat in cbc :
        if date1 is not None and date2 is not None:
            if date1<=pat.date<=date2:
                cbc_table.append([pat.date,float(f"{pat.wbc:.5f}"),float(f"{pat.rbc:.5f}"),float(f"{pat.hemoglobin:.5f}"),float(f"{pat.hematocrit:.5f}"),float(f"{pat.mcv:.5f}"),float(f"{pat.mch:.5f}"),float(f"{pat.mchc:.5f}"),float(f"{pat.rdw:.5f}"),float(f"{pat.platelets:.5f}"),float(f"{pat.neurophils:.5f}"),float(f"{pat.lymphs:.5f}"),float(f"{pat.monocytes:.5f}")])
        else:
            cbc_table.append([pat.date,float(f"{pat.wbc:.5f}"),float(f"{pat.rbc:.5f}"),float(f"{pat.hemoglobin:.5f}"),float(f"{pat.hematocrit:.5f}"),float(f"{pat.mcv:.5f}"),float(f"{pat.mch:.5f}"),float(f"{pat.mchc:.5f}"),float(f"{pat.rdw:.5f}"),float(f"{pat.platelets:.5f}"),float(f"{pat.neurophils:.5f}"),float(f"{pat.lymphs:.5f}"),float(f"{pat.monocytes:.5f}")])	
    #print(cbc_table)

    meta_table = []
    for pat in meta :
        if date1 is not None and date2 is not None:
            if date1<=pat.date<=date2:
                meta_table.append([pat.date,float(f"{pat.glucose:.5f}"),float(f"{pat.creatinine:.5f}"),float(f"{pat.sodium:.5f}"),float(f"{pat.potassium:.5f}"),float(f"{pat.chloride:.5f}"),float(f"{pat.carbon_dioxide:.5f}")])
        else:
            meta_table.append([pat.date,float(f"{pat.glucose:.5f}"),float(f"{pat.creatinine:.5f}"),float(f"{pat.sodium:.5f}"),float(f"{pat.potassium:.5f}"),float(f"{pat.chloride:.5f}"),float(f"{pat.carbon_dioxide:.5f}")])
    #print(meta_table)
    mri_table = []
    for pat in mri :
        if date1 is not None and date2 is not None:
            if date1<=pat.date<=date2:
                mri_table.append([pat.date,pat.mri.url])
        else:
            mri_table.append([pat.date,pat.mri.url])
    #print(mri_table)
    xray_table = []
    for pat in xray :
        if date1 is not None and date2 is not None:
            if date1<=pat.date<=date2:
                xray_table.append([pat.date,pat.xray.url])
        else:
            xray_table.append([pat.date,pat.xray.url])

    val=[]
    for x in prescriptions:
	    for y in prescriptmeds:
		    if x.prescript_id==y.prescript_id.prescript_id:
				#print("These should be same: ",x.pid.pid, Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid)
			    date=x.date

			    if(date1 is not None and date2 is not None):
				    if(date1<=date<=date):
					    val.append([x.pid.name,x.did.name,y.medid.name,y.description,date])

			    else:
				    val.append([x.pid.name,x.did.name,y.medid.name,y.description,date])

	#print(request.user,UserProfile.objects.get(user=request.user).id)

    dicts={'val':val,'cbc':cbc_table,'meta':meta_table,'mri':mri_table,'xray':xray_table,'p':p.pid}

    return render(request,"doctor_showhistory.html", dicts)
def doctorSignup(request):
    if(request.POST.get('fname') is None):
        
        return render(request, "form_doctor_signup.html")
    else:
        print("OOOOKKKK")
        fname       = request.POST["fname"]
        lname       = request.POST["lname"]
        gender      = request.POST["gender"]
        dob = dt.strptime(request.POST["dob"],"%Y-%m-%d").date()
        country     = request.POST["country"]
        profile_id  = UserProfile.objects.get(id=request.POST["profile_id"])

        DoctorObject = Doctor.objects.create(name=fname,surname=lname,gender=gender,dob=dob,country=country,profile_id=profile_id)

        return render(request, "doctor_home.html")
