from django.shortcuts import redirect, render
from .models import *
from django.db import connection
from lab.models import LabTest
from Account.models import UserProfile
import re
from datetime import datetime as dt
from doctor.models import doctorRequestsTable
from django.db.models import F
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User,auth

# Create your views here.
def index(request):
    return render(request, "index.html")

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

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

def requestLab(request):
	if request.method == 'POST':
		test = request.POST["testtype"]
		pid = Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid
		indate = request.POST["labdate"]
		pat = Patient(pid=pid)
		temp = LabTest.objects.create(pid=pat, test=test, date=indate)
		temp.save()
		return render(request, "requestLab.html")
	else:
		return render(request, "requestLab.html")


def showHistory(request):
	prescriptions=[]
	prescriptmeds=[]
	cbc = []
	meta = []
	mri = []
	xray = []	
	
	if(request.user.is_authenticated and UserProfile.objects.get(user=request.user).profile_type=='Patient'):
		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=Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid)
	prescriptmeds = Prescriptmed.objects.all().select_related('prescript_id','medid')
	cbc = Commonbloodcount.objects.filter(pid=Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid)
	meta = Basicmetabolismpanel.objects.filter(pid=Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid)
	mri = Mri.objects.filter(pid=Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid)
	xray = Xray.objects.filter(pid=Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid)
	patient_name = Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).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])
	#print(xray_table)

	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}

	return render(request,"showHistory.html", dicts)

def patientGrant(request):
	if request.method == 'POST':
		pid = request.POST["fill"]
		temp_doctor = doctorRequestsTable.objects.get(id=pid)
		# print(temp_doctor)
		temp = patientGrantTable.objects.create(pid=temp_doctor.pid, docid=temp_doctor.docid)
		temp.save()
		temp_doctor.delete()
		patientid = Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid
		test_list = { 'test_list' : doctorRequestsTable.objects.filter(pid=patientid) }
		return render(request, "patientApprove.html", test_list)
	else:
		patientid = Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid
		# doctorids = doctorRequestsTable.objects.filter(pid=patientid).values('docid')
		# for i in doctorids:
		# 	print(i.update('docid', i.get('docid'), Doctor.objects.get(did=i.get('docid')).name))
		# for i in doctorRequestsTable.objects.filter(pid=patientid):
		# 	print(i.docid)
		test_list = { 'test_list' : doctorRequestsTable.objects.filter(pid=patientid) }
		return render(request, "patientApprove.html", test_list)

def grantedRequests(request):
	if request.method == 'POST':
		pid = request.POST["fill"]
		temp_doctor = patientGrantTable.objects.get(id=pid)
		# print(temp_doctor)
		temp_doctor.delete()
		test_list = { 'test_list' : patientGrantTable.objects.filter(pid=pid) }
		return render(request, "grantedRequests.html", test_list)
	else:
		patientid = Patient.objects.get(profile_id=UserProfile.objects.get(user=request.user).id).pid
		test_list = { 'test_list' : patientGrantTable.objects.filter(pid=patientid) }
		return render(request, "grantedRequests.html", test_list)

def patientSignup(request):
	if(request.POST.get('fname') is None):
		print("OOOOKKKK")
		return render(request, "form_patient_signup.html")
	else:
		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"]
		street		= request.POST["street"]
		city		= request.POST["city"]
		state		= request.POST["state"]
		postal		= request.POST["pinCode"]
		profile_id	= UserProfile.objects.get(id=request.POST["profile_id"])

		PatientObject = Patient.objects.create(name=fname,surname=lname,gender=gender,date=dob,country=country,street_address=street,city=city,postal=postal,profile_id=profile_id)

		return render(request, "showHistory.html")