from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib.auth import authenticate  , login , logout
from django.contrib.auth.models import User
from theblog.models import alpha , total
# Create your views here.

def register(request):
	if request.method == 'POST':
		username = request.POST['username'].strip()
		email    = request.POST['email'].strip()
		password1 = request.POST['password1'].strip()
		password2 = request.POST['password2'].strip()
		
		if len(username) == 0 or len(email) == 0:
			return render(request, 'users/register.html' , {'message':"Username or Email Can't be empty."})	
		elif User.objects.filter(username=username).exists():
			return render(request, 'users/register.html' , {'message':'Username is already taken.'})
		elif User.objects.filter(email=email).exists():
			return render(request, 'users/register.html' , {'message':'Already have an account with this E-mail id.'})
		elif password1 != password2:
			return render(request, 'users/register.html' , {'message':"Passwords don't match."})
		
		else:
			user = User.objects.create_user(username=username,password=password1,email=email)
			user.save()
			login(request,user)
			x = alpha(userid = request.user)
			x.save()
			y = total(userid = request.user)
			y.save()
			return redirect('/')
	else:
		return render(request , 'users/register.html', {'message':''})
def loginmanual(request):
	if request.method == 'POST':
		username = request.POST['username'].strip()
		password = request.POST['password'].strip()
		user = authenticate(request , username=username, password=password)
		if user is not None:
			login(request,user)
			return redirect ('/')
		else:
	 		return render(request , 'users/login.html' , {'message':'Invalid credentials. Either username or password is incorrect'})
	else:
	 return render(request , 'users/login.html' , {'message':''})


def logoutmanual(request):
	logout(request)
	return redirect('/')
