from django.shortcuts import render
from django.contrib.auth import login, authenticate
from django.contrib import messages
from django.contrib.auth.models import User,auth
from django.shortcuts import render, redirect
from .models import UserProfile

# Create your views here.

def login(request):
	if request.method == 'POST':

		username = request.POST['username']
		password = request.POST['password']

		user=authenticate(username=username,password=password)

		print("COOL",username,password)

		if user is not None:
			auth.login(request,user)
			if UserProfile.objects.get(user=request.user).profile_type == 'Doctor':
				return redirect('doctor/doctorhome')
			elif UserProfile.objects.get(user=request.user).profile_type == 'Patient':
				return redirect('patient/showHistory')
			else:
				return redirect('lab/lab_index')
		else:
			messages.info(request,'Invalid Username/Password')
			return redirect('register')

def logout(request):
	auth.logout(request)
	return redirect('register')

def register(request):
	if request.method == 'POST':

		#messages.info(request,'Welcome')

		username = request.POST['username']
		email 	 = request.POST['email']
		password = request.POST['password']
		age 	 = request.POST['age']
		profile_type = request.POST['profile_type']

		if User.objects.filter(username=username).exists():
			messages.info(request,'Username already taken')
			return redirect('register')

		user=User.objects.create_user(username=username,email=email,password=password)
		user.save()
		UserProfileInstance = UserProfile.objects.create(user=user,age=int(age),profile_type=profile_type)

		print("1")
		user=authenticate(username=username,password=password)
		if user is not None:
			auth.login(request,user)
		print("2")

		profile_id=UserProfile.objects.get(user=request.user).id
		val={'profile_id':profile_id}
		print(profile_id)

		dicts={'profile_id':profile_id}
		print("User {} created with profile_ID {}".format(username,UserProfile.objects.get(user=user).id))
		
		if profile_type=='Patient':
			return render(request,'form_patient_signup.html',dicts)
		elif profile_type=='Doctor':
			return render(request,'form_doctor_signup.html',dicts)
		else:
			return redirect('lab/lab_index')

	return render(request,'login.html')

