from django.http.response import JsonResponse

from BookStore import error
from BookStore.function import check_login, check_method, generate_token, \
    get_username_by_token, get_post_json

from user.models import User, Address


# Create your views here.

@check_method('POST')
def register_view(request):
    post = get_post_json(request)
    print(post)
    username = post.get('user_id')
    password = post.get('password')

    # 判断参数是否存在
    if username is None or password is None:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    # 判断用户名和密码是否合法
    if len(username) < 3 or len(username) > 8 or \
            len(password) < 6 or len(password) > 18:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    # 判断是否在数据库中已存在
    try:
        User.objects.get(username=username)

        code, message = error.user_id_already_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 若未存在则新建一条记录
    except User.DoesNotExist:
        try:
            User.objects.create(username=username, password=password)
            return JsonResponse({
                'message': 'ok',
            })

        # 若创建失败
        except Exception as e2:
            print('Create(Insert) error! ', e2)
            code, message = error.database_error()
            return JsonResponse({
                'message': message,
            }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)


@check_login
@check_method('POST')
def unregister_view(request):
    post = get_post_json(request)
    username = get_username_by_token(request)

    if post.get('user_id') is None:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    if post.get('user_id') != username:
        code, message = error.authorization_fail()
        return JsonResponse({
            'message': message,
        }, status=code)

    password = post.get('password')

    try:
        user = User.objects.get(username=username)
        if password == user.password:
            user.delete()
            return JsonResponse({
                'message': 'ok',
            })
        else:
            code, message = error.authorization_fail()
            return JsonResponse({
                'message': message,
            }, status=code)

    # 若用户名不存在则返回错误
    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message', message,
        }, status=code)


@check_method('POST')
def login_view(request):
    post = get_post_json(request)
    username = post.get('user_id')
    password = post.get('password')
    terminal = post.get('terminal')

    # 判断参数是否存在
    if username is None or password is None or terminal is None:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    # 判断是否在数据库中已存在，再判断密码是否正确
    try:
        user = User.objects.get(username=username)
        if password == user.password:
            # 生成token
            token = generate_token(post)
            return JsonResponse({
                'message': 'ok',
                'token': token,
            })
        else:
            code, message = error.authorization_fail()
            return JsonResponse({
                'message': message,
            }, status=code)

    # 若用户名不存在则返回错误
    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message', message,
        }, status=code)


@check_login
@check_method('POST')
def logout_view(request):
    post = get_post_json(request)

    if post.get('user_id') is None:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    # 判断token是否为当前用户
    username = get_username_by_token(request)
    if post.get('user_id') == username:
        return JsonResponse({
            'message': 'ok',
        })
    else:
        code, message = error.authorization_fail()
        return JsonResponse({
            'message': message,
        }, status=code)


@check_login
@check_method('POST')
def password_view(request):
    post = get_post_json(request)
    user_id = post.get('user_id')
    old_password = post.get('oldPassword')
    new_password = post.get('newPassword')

    # 判断参数是否正确
    if user_id is None or old_password is None or new_password is None:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    # 判断token是否为当前用户
    username = get_username_by_token(request)
    if user_id != username:
        code, message = error.authorization_fail()
        return JsonResponse({
            'message': message,
        }, status=code)

    # 从数据库中获得user，判断其密码是否一致
    try:
        user = User.objects.get(username=username)
        if old_password == user.password:
            user.password = new_password
            user.save()
            return JsonResponse({
                'message': 'ok',
            })

        # 若原密码错误
        else:
            code, message = error.authorization_fail()
            return JsonResponse({
                'message': message,
            }, status=code)

    # 若用户名不存在则返回错误
    except User.DoesNotExist:
        code, message = error.user_id_already_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message', message,
        }, status=code)


@check_login
@check_method('GET')
def info_view(request):
    username = get_username_by_token(request)

    try:
        user = User.objects.get(username=username)
        return JsonResponse({
            'message': 'ok',
            'info': user.info_json(),
        })

    # 若用户名不存在则返回错误
    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message', message,
        }, status=code)


@check_login
@check_method('POST')
def info_modify_view(request):
    user_id = get_username_by_token(request)

    # 获取参数
    post = get_post_json(request)
    email = post.get('email')
    gender = post.get('gender')
    phone_number = post.get('phone_number')
    avatar = request.FILES.get('avatar')

    if gender:
        if gender != '男' and gender != '女' and gender != '未设置':
            code, message = error.invalid_parameter()
            return JsonResponse({
                'message': message
            }, status=code)

    try:
        user = User.objects.get(username=user_id)
        if email:
            user.email = email
        if phone_number:
            user.phoneNumber = phone_number
        if avatar:
            user.avatar = avatar
        if gender:
            user.gender = gender

        user.save()
        return JsonResponse({
            'message': 'ok',
        })

    # 用户ID不存在
    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(user_id)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)


@check_login
@check_method('POST')
def add_address_view(request):
    username = get_username_by_token(request)

    post = get_post_json(request)
    name = post.get('name')
    phone_number = post.get('phone_number')
    address = post.get('address')

    # 若无参数
    if name is None or phone_number is None or address is None:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    try:
        user = User.objects.get(username=username)

        try:
            Address.objects.create(user=user, name=name, phoneNumber=phone_number, address=address)
            return JsonResponse({
                'message': 'ok',
            })
        except Exception as e2:
            print('Create(Insert) error! ', e2)
            code, message = error.database_error()
            return JsonResponse({
                'message': message,
            }, status=code)

    # 若用户ID不存在
    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)


@check_login
@check_method('POST')
def delete_address_view(request):
    username = get_username_by_token(request)

    post = get_post_json(request)
    address_id = post.get('address_id')

    # 若无参数
    if address_id is None:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    try:
        user = User.objects.get(username=username)
        address = Address.objects.get(id=address_id, user=user)

        try:
            address.delete()
            return JsonResponse({
                'message': 'ok',
            })
        except Exception as e2:
            print('Delete error! ', e2)
            code, message = error.database_error()
            return JsonResponse({
                'message': message,
            }, status=code)

    # 若用户ID不存在
    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 若address_id不存在
    except Address.DoesNotExist:
        code, message = error.address_id_doesnt_exist(address_id)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)
