import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .form import UserNameForm
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.contrib.auth.models import User
from .models import Friends, FriendRequest
from infrastructure.consumers import knock_knock

DEBUG = True


# 批处理流程
# def more_clean(request, form, html):
#     if request.method == 'POST':
#         user_login_form = form(request.POST)
#         if user_login_form.is_valid():
#             # 清洗出合法的数据
#             data = user_login_form.cleaned_data
#             return data
#     elif request.method == 'GET':
#         if DEBUG:
#             form = form()
#             context = {'form': form}
#             return render(request, html, context)
#
#     else:
#         return HttpResponse(status=400)


# 获取好友列表
@csrf_exempt
@login_required(login_url='/account/login/')
def friends_list(request):
    if request.method == 'POST':
        # 查找双向好友关系
        friends = Friends.objects.filter(user__username=request.user.username)
        response = []
        for friend in friends:
            response.append(friend.friend.username)
        friends = Friends.objects.filter(friend__username=request.user.username)
        for friend in friends:
            response.append(friend.user.username)
        return HttpResponse(json.dumps(response), status=200)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'get_user_list.html')
    else:
        return HttpResponse(status=400)


#  添加好友（通过ws发送给被请求方信息，返回等待对方回应中）
@csrf_exempt
@login_required(login_url='/account/login/')
def add_friend(request):
    if request.method == 'POST':
        user_name_form = UserNameForm(request.POST)
        if user_name_form.is_valid():
            data = user_name_form.cleaned_data
            # 查找是否有此人
            user = User.objects.filter(username=data['username'])
            if user:
                # 查找双向好友关系
                friend_1 = Friends.objects.filter(user__username=data['username'])
                friend_2 = Friends.objects.filter(friend__username=data['username'])
                if friend_1 or friend_2:
                    # 二者已是好友关系
                    return HttpResponse(status=421)
                else:
                    friend_request = FriendRequest.objects.filter(requester__username=request.user.username)
                    friend_request = friend_request.filter(receiver__username=data['username'])
                    if friend_request:
                        knock_knock(data['username'], 'get_friends_requests')
                        return HttpResponse(status=200)
                    else:
                        new_friend_request = FriendRequest()
                        new_friend_request.requester = request.user
                        new_friend_request.receiver = User.objects.filter(username=data['username']).get()
                        new_friend_request.save()
                        return HttpResponse(status=200)
            else:
                return HttpResponse(status=422)
        else:
            return HttpResponse(status=400)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'add_friend.html')
    else:
        return HttpResponse(status=400)


@csrf_exempt
@login_required(login_url='/account/login/')
def get_friend_request(request):
    # 查找目前有哪些请求
    friend_requests = FriendRequest.objects.filter(receiver__username=request.user.username)
    response = []
    for friend_request in friend_requests:
        response.append(friend_request.requester.username)
    return HttpResponse(json.dumps(response), status=200)


# 由于ws不是很确定，先闲置
# 同意添加好友，
@login_required(login_url='/account/login/')
def accept_friend(request):
    if request.method == "POST":
        user_name_form = UserNameForm(request.POST)
        if user_name_form.is_valid():
            data = user_name_form.cleaned_data
            friend_requests = FriendRequest.objects.filter(receiver__username=request.user.username)
            friend_requests = friend_requests.filter(requester__username=data['username'])
            if friend_requests:
                Friends.objects.create(user=User.objects.filter(username=data['username']).get(),
                                       friend=User.objects.filter(username=request.user.username).get(),
                                       status=1)
                for friend_request in friend_requests:
                    friend_request.delete()
                    return HttpResponse(status=200)
            else:
                return HttpResponse(status=400)
        else:
            return HttpResponse(status=400)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'accept_friend.html')
    else:
        return HttpResponse(status=400)


# 获取详细好友信息
# @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 = {'result': "do not exist"}
#         return HttpResponse(json.dumps(response))
#
#     if len(friendsTemp):
#         response = {"data": friendsTemp, "result": "好友列表"}
#         return HttpResponse(json.dumps(response))
#     else:
#         response = {"result": "wrong"}
#         return HttpResponse(json.dumps(response))


@csrf_exempt
def delete_friend(request):
    if request.method == 'POST':
        user_name_form = UserNameForm(request.POST)
        if user_name_form.is_valid():
            data = user_name_form.cleaned_data
            try:
                temp_friends_1 = Friends.objects.filter(
                    user=User.objects.filter(username=data["username"]).get(), friend=request.user)
                temp_friends_2 = Friends.objects.filter(
                    friend=User.objects.filter(username=data["username"]).get(), user=request.user)
            except Friends.DoesNotExist:
                return HttpResponse(status=422)
            if not temp_friends_1 and not temp_friends_2:
                return HttpResponse(status=400)
            if temp_friends_1:
                for temp_friend in temp_friends_1:
                    temp_friend.delete()
            if temp_friends_2:
                for temp_friend in temp_friends_2:
                    temp_friend.delete()
            return HttpResponse(status=200)
        else:
            return HttpResponse(status=400)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'delete_friend.html')
