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

def login(request):
    if request.method=='POST':
        username=request.POST['username']
        password=request.POST['password']
        user=auth.authenticate(username=username,password=password)
        if user is not None:
            auth.login(request,user)
            return redirect('home')
        else:
            messages.info(request,'invalid credentials')
    return render(request,'login.html')
def logout(request):
    auth.logout(request)
    return redirect('login')

def home(request):
    return render(request,'home.html')


def register(request):
    if request.method=='POST':
        username=request.POST['username']
        lastname=request.POST['LastName']
        email = request.POST['email']
        password=request.POST['password']
        confirmpassword = request.POST['ConfirmPassword']
        if password==confirmpassword:
            if User.objects.filter(username=username).exists():
                messages.info(request,"user name taken!!")
                return redirect('register')
            elif User.objects.filter(email=email).exists():
                messages.info(request,"email-id taken")
                return redirect('register')
            else:
                user=User.objects.create_user(username=username,email=email,password=password)
                user.save()
                messages.info(request,'user created succesfully')
                return redirect('register')
        else:
            messages.info(request,'passwords not matching!')
        return redirect('register')
    else:
        return render(request, 'register.html')
