import json
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .form import UserRequestForm, UserListForm
from .models import friends


# 批处理流程
def more_clean(request, form):
    if request.method == 'POST':
        user_login_form = form(request.POST)
        if user_login_form.is_valid():
            # 清洗出合法的数据
            data = user_login_form.cleaned_data
            return data
    else:
        response = ['illegal input']
        return HttpResponse(json.dumps(response))


# 获取好友列表
@csrf_exempt
def friendsList(request):
    data = more_clean(request, UserListForm)
    if data.get('token') != 'token':
        response = ['there has a mistake, please provide illegal token']
        return HttpResponse(json.dumps(response))
    else:
        try:
            friendsTemp = friends.objects.filter(whomfriend=data['username'])
            return HttpResponse(json.dumps(friendsTemp))
        except friends.DoesNotExist:
            response = ['this user do not exist']
            return HttpResponse(json.dumps(response))


#  添加好友（通过ws发送给被请求方信息，返回等待对方回应中）
# @csrf_exempt
# def addFriend(request):
# 由于ws不是很确定，先闲置


# 同意添加好友，
def acceptFriend(request):
    data = more_clean(request, UserRequestForm)
    if request.method == "POST":
        try:
            friends.objects.create(username=data["username"], whomfriend=data["otherUsername"], token=data["token"],
                                   status=1)
            response = ["add successfully"]
            return HttpResponse(json.dumps(response))
        except:
            response = ["add failed"]
            return HttpResponse(json.dumps(response))


# 获取详细好友信息
@csrf_exempt
def friendDetail(request, pk):
    data = more_clean(request, UserRequestForm)
    try:
        loginUserid = int(data["username"])
        friendsTemp = friends.objects.get(whomfriend=loginUserid, userid=pk)

    except friends.DoesNotExist:
        response = ["do not exist"]
        return HttpResponse(json.dumps(response))

    if len(friendsTemp):
        response = [friendsTemp]
        return HttpResponse(json.dumps(response))
    else:
        response = ["wrong"]
        return HttpResponse(json.dumps(response))


@csrf_exempt
def deleteFriend(request):
    data = more_clean(request, UserRequestForm)
    try:
        tempFriend = friends.objects.get(
            username=data["username"], whomfriend=data["otherUsername"])
        tempFriend.clear()
        response = ["delete success"]
        return HttpResponse(json.dumps(response))
    except:
        response = ["delete failed"]
        return JsonResponse(response)
