from django.shortcuts import render,redirect
from django.contrib.auth.models import User,auth#(auth will be for the login part)
from django.contrib import messages 
from django.core.mail import send_mail

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)  #given access for login if it exist
            send_mail('User Login',f'User name is {username} has been logged in','firstproject459@gmail.com',['ompatel9923@gmail.com'],fail_silently=False)
            return redirect('/')
        else:
            messages.info(request,'Invalid Credentials')
            return redirect('login')

    else:

        return render(request,'login.html')    
# Create your views here.
def register(request):
    if request.method=="POST":
        first_name=request.POST['first_name']  #this first name is the one which is inside name of input tag
        last_name=request.POST['last_name']
        username=request.POST['username']
        email=request.POST['email']
        password1=request.POST['password1']
        password2=request.POST['password2']
        if password1==password2:
            if User.objects.filter(username=username).exists():
                messages.info(request,'username taken')
                return redirect('register')
            elif User.objects.filter(email=email).exists():  
                messages.info(request,'email exists')
                return redirect('register')
            else:      
                user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name)
                user.save()
                messages.info(request,'user created')
                return redirect('login')
        else:
            messages.info(request,'invalid password')
            return redirect('register')
        return redirect('/')
    else:
        return render(request,'register.html')

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