import re

from django.contrib.auth import login as set_auth
from django.contrib.auth import logout as remove_auth
from django.contrib.auth.models import User
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse, HttpResponseRedirect

from config import ALLOW_NEW_USERS
from tauth.models import TUser

from .helper import render_template


def index(request: WSGIRequest) -> HttpResponse:
    if request.user.is_authenticated:
        return render_template(
            request, "index.html",
            username=request.user.get_username()
        )
    return render_template(
        request, "noauth/index.html",
        new_users=ALLOW_NEW_USERS
    )

def signup(request: WSGIRequest) -> HttpResponse:
    if request.user.is_authenticated:
        return HttpResponseRedirect("/")

    if ALLOW_NEW_USERS:
        if request.method == "POST":
            username = (request.POST.get("username") or "").lower().strip()
            password = (request.POST.get("password") or "")
            error = None

            if len(username) < 2 or len(username) > 30 or not re.match("^[a-z0-9_][a-z0-9_\\-]{0,28}[a-z0-9_]$", username):
                error = "Invalid username"

            elif len(password) < 6 or len(password) > 100 or not (any([i.isalpha() for i in password]) and any([i.isnumeric() for i in password]) and any([not i.isalnum() for i in password])):
                error = "Invalid password"

            else:
                try:
                    u = User.objects.create_user(
                        username=username,
                        password=password
                    )
                except User.DoesNotExist:
                    error = "Username already in use"
                else:
                    TUser.objects.create(user=u)

                    set_auth(request, u)
                    return HttpResponseRedirect("/")

            return render_template(
                request, "noauth/signup.html",
                title="Sign Up",
                error=error,
                repopulate={
                    "username": username
                }
            )

        return render_template(
            request, "noauth/signup.html",
            title="Sign Up"
        )

    return render_template(
        request, "404.html"
    )

def login(request: WSGIRequest) -> HttpResponse:
    return render_template(
        request, "noauth/login.html",
        title="Log In"
    )
