from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm
from django.contrib.auth.models import User
from game.models import Player


def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Your account has been created! You are now able to log in')
            user = User.objects.get(username = username)
            #user = User.objects.get(username = request.POST['user'])
            #user.player_set.create(name = user.username) # set_create calismiyor
            player = Player(name=username)
            player.user = user
            player.save()
            return redirect('login')
    else: #Create empty form
        form = UserRegisterForm()

    
    return render(request, 'users/register.html', {'form': form})


@login_required
def profile(request):
    return render(request, 'users/profile.html')
