from django.contrib.auth import login, logout
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.shortcuts import render, redirect
from django.views.generic import TemplateView

from users.forms import UserRegisterForm, UserLoginForm
from users.models import Player
from users.util import bloonsa_util, actions


class LoginView(TemplateView):

    def get(self, request, *args, **kwargs):
        form = UserLoginForm()
        return render(request=request, template_name="users/login.html", context={"form": form})

    def post(self, request, *args, **kwargs):
        form = UserLoginForm(data=request.POST)
        if not form.is_valid():
            return render(request=request, template_name="users/login.html", context={"form": form})
        user = form.get_user()
        player = bloonsa_util.init_player(request=request)
        login(request=request, user=user)
        bloonsa_util.log(player=player,
                         action=actions.login)
        return redirect("bloonsa_game:game")


class RegisterView(TemplateView):

    def get(self, request, *args, **kwargs):
        form = UserRegisterForm()
        return render(request=request, template_name="users/register.html", context={"form": form})

    def post(self, request, *args, **kwargs):
        form = UserRegisterForm(request.POST)
        if not form.is_valid():
            return render(request=request, template_name="users/register.html", context={"form": form})
        user = form.save()
        player = bloonsa_util.init_player(request=request)
        login(request=request, user=user)
        bloonsa_util.log(player=player,
                         action=actions.login)
        return redirect("bloonsa_game:game")



class LogoutView(TemplateView):

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            bloonsa_util.tag_player(request=request)
            bloonsa_util.log(request=request,
                             action=actions.logout)
            logout(request)
        return redirect("bloonsa_game:game")


