import json

from django.contrib.auth.models import User
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse

from tauth.settings import config


def get_username(request: WSGIRequest) -> HttpResponse:
    try:
        if request.GET.get("token") == config["services"][request.GET.get("service")]["token"]:
            authenticated = request.user.is_authenticated
            return HttpResponse(
                json.dumps({
                    "success": True,
                    "authenticated": authenticated,
                    "username": request.user.get_username() if authenticated else None
                }),
                content_type="application/json"
            )
    except KeyError:
        ...

    return HttpResponse(
        json.dumps({
            "success": False
        }),
        content_type="application/json",
        status=401
    )

def username_exists(request: WSGIRequest) -> HttpResponse:
    try:
        if request.GET.get("token") == config["services"][request.GET.get("service")]["token"]:
            exists = True
            try:
                User.objects.get(username=request.GET.get("username"))
            except User.DoesNotExist:
                exists = False

            return HttpResponse(
                json.dumps({
                    "success": True,
                    "exists": exists
                }),
                content_type="application/json"
            )

    except KeyError:
        ...

    return HttpResponse(
        json.dumps({
            "success": False
        }),
        content_type="application/json",
        status=401
    )
