from django.shortcuts import render

# Create your views here.

from datetime import datetime, time
from .models import User, LoginToken
from django.http import JsonResponse, HttpResponse
from rest_framework.decorators import api_view
from django.middleware.csrf import rotate_token


def auth_with_username_or_email(username, password):
    if '@' in username:
        user = User.objects.get(email=username, password=password)
    else:
        user = User.objects.get(username=username, password=password)
    return user


@api_view(['POST'])
def register(request):
    username = request.data.get('username', '')
    password = request.data.get('password', '')
    email = request.data.get('email', '')

    try:
        User.objects.create(username=username, password=password, email=email)
        print('注册成功')
        return JsonResponse({'code': 200})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 303, 'error': str(e)}, status=303)


@api_view(['POST'])
def login(request):
    username = request.data.get('username', '')
    password = request.data.get('password', '')
    token = request.data.get('token', '')

    try:
        user = auth_with_username_or_email(username, password)
        print(user)
    except Exception as e:
        print(e)
        print('用户名或密码错误')
        return JsonResponse({'code': 303, 'error': '用户名或密码错误'}, status=303)

    print(f'token = {token}')
    if user.check_token(token):
        try:
            user_token = user.tokens.get(token=token)
            print('已登录')
            user_token.delete()
            # return JsonResponse({'code': 303, 'msg': '已登录'}, status=303)
        except Exception as e:
            print('token无效')
    else:
        print('token已过期')

    user.last_login = datetime.now()

    new_token = user.make_token()
    user_token = LoginToken()
    user_token.user = user
    user_token.token = new_token
    user_token.save()

    if hasattr(request, '_user'):
        print('设置reqeust._user')
        request.user = user

    print('登录成功')
    print(f'new_token = {new_token}')
    return JsonResponse({'code': 200, 'token': new_token})


@api_view(['POST'])
def logout(request):
    username = request.data.get('username', '')
    token = request.data.get('token', '')
    try:
        user = User.objects.get(username=username)
        try:
            user_token = user.tokens.get(token=token)
            user_token.delete()
        except Exception as e:
            print(e)
            print('token无效')
        return JsonResponse({'code': 200})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 303, 'error': str(e)}, status=303)


@api_view(['POST'])
def reset_password(request):
    username = request.data.get('username', '')
    password = request.data.get('password', '')
    try:
        user = User.objects.get(username=username)
        token = request.data.get('token')
        if token:
            print(f'token={token}')
            if user.check_token(token):
                # 重置密码
                print("验证码有效")
                user.password = password
                user.save()
                return JsonResponse({'code': 200})
            else:
                print("验证码无效")
                return JsonResponse({'code': 303, 'error': '验证码错误'}, status=303)
        else:
            # 发送验证码
            token = user.make_token()
            print(f'')
            print(f'发送验证码 email = {user.email} token = {token}')
            user.send_email('ST网盘重置密码验证码', token)
            return JsonResponse({'code': 200})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 303, 'error': str(e)}, status=303)
