from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm


def register(request):

	if request.method == 'POST': #Execute the below code only if something has been submitted through POST.
		form = UserRegisterForm(request.POST)
		if form.is_valid():
			form.save() #automatically updates the database with the registration values
			username = form.cleaned_data.get('username') #Cleans the data to prevent SQLi type attacks.
			messages.success(request, f'Account created for {username}! You can now log in!')
			return redirect('../login')
	else:
		form = UserRegisterForm() #else, display just the regular form for the user to register.
	return render(request, 'users/register.html', {'form' : form}) #in both cases, it'll return the register.html template at templates/users/register.html



def login(request):
	return render(request, 'users/login.html')


@login_required
def profile(request):

	if request.method == 'POST':
		u_form = UserUpdateForm(request.POST, instance=request.user)
		p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
		
		if u_form.is_valid() and p_form.is_valid():
			u_form.save()
			p_form.save()
			messages.success(request, f'Your account has been updated!')
			return redirect('profile')


	else:
		u_form = UserUpdateForm(instance=request.user)
		p_form = ProfileUpdateForm(instance=request.user.profile)

	context = {
		'u_form' : u_form,
		'p_form' : p_form
	}

	return render(request, 'users/profile.html', context)
