from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
import json
from friends.models import Friends
from infrastructure.consumers import knock_knock
import time

from .form import StoreDataForm
from .models import Message
from django.http import JsonResponse
from django.db.models import Q

DEBUG = True


# 批处理流程
# 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 = {'result': 'illegal input'}
#         return HttpResponse(json.dumps(response))


#
# 存储消息到表中
@csrf_exempt
@login_required(login_url='/account/login/')
def send_message(request):
    if request.method == 'POST':
        store_data_form = StoreDataForm(request.POST)
        if store_data_form.is_valid():
            data = store_data_form.cleaned_data
            user = User.objects.filter(username=data['toUsername'])
            if user:
                temp_friends_1 = Friends.objects.filter(
                    user=User.objects.filter(username=data["toUsername"]).get(), friend=request.user)
                temp_friends_2 = Friends.objects.filter(
                    friend=User.objects.filter(username=data["toUsername"]).get(), user=request.user)
                if temp_friends_1 or temp_friends_2:
                    Message.objects.create(
                        fromUser=request.user,
                        toUser=user.get(),
                        plaintext=data['plaintext'],
                    )
                    knock_knock(user.get().username, 'request_message')
                    return HttpResponse(status=200)
                else:
                    return HttpResponse(status=423)
            else:
                return HttpResponse(status=422)
        else:
            return HttpResponse(status=400)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'send_message.html')
    else:
        return HttpResponse(status=400)
    # try:
    #     Message.objects.create(
    #         date=post_data["date"],
    #         belongUserid=postData["belongUserid"],
    #         fromUserid=postData["fromUserid"],
    #         toUserid=postData["toUserid"],
    #         EphemeralPub=postData["EphemeralPub"],
    #         plaintext=postData["plaintext"],
    #         EphemeralPri=postData["EphemeralPri"])
    #     response = {"result": "添加成功"}
    #     return JsonResponse(response)
    # except:
    #     response = {"result": "添加失败！"}
    #     return JsonResponse(response)


# 适用于设备的漫游消息
@csrf_exempt
@login_required(login_url='/account/login/')
def filter_messages(request):
    if request.method == 'POST':
        data = request.POST
        user = User.objects.filter(username=data['username'])
        if user:
            user = user.get()
            temp_friends_1 = Friends.objects.filter(
                user=user, friend=request.user)
            temp_friends_2 = Friends.objects.filter(
                friend=user, user=request.user)
            if temp_friends_1 or temp_friends_2:
                # to_user = User.objects.filter(username=data['username'])
                # messages = Message.objects.filter(
                #     (Q(fromUser=to_user) & Q(toUser=request.user)) |
                #     (Q(fromUser=request.user) & Q(toUser=to_user))
                # ).order_by("date")
                response = []
                messages = Message.objects.filter(fromUser__username=data['username'],
                                                  toUser__username=request.user.username)
                for message in messages:
                    message_dict = {'from_user_name': message.fromUser.username, 'plaintext': message.plaintext,
                                    'to_user_name': request.user.username,
                                    'date': time.mktime(message.date.timetuple())}
                    response.append(message_dict)
                messages = Message.objects.filter(toUser__username=data['username'],
                                                  fromUser__username=request.user.username)
                for message in messages:
                    message_dict = {'from_user_name': message.fromUser.username, 'plaintext': message.plaintext,
                                    'to_user_name': request.user.username,
                                    'date': time.mktime(message.date.timetuple())}
                    response.append(message_dict)
                return HttpResponse(json.dumps(response), status=200)
            else:
                return HttpResponse(status=423)
        else:
            return HttpResponse(status=422)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'filter_message.html')
    else:
        return HttpResponse(status=400)
    # try:
    #     loginUserid = data["fromUsername"]
    #     messagesTemp = list(Message.objects.filter(
    #
    #         (Q(fromUserid=pk) & Q(toUserid=loginUserid) & Q(belongUserid=loginUserid)) |
    #         (Q(fromUserid=loginUserid) & Q(toUserid=pk) & Q(belongUserid=loginUserid))
    #     ).order_by("date"))
    #     response = {"result": "已发送", "data": messagesTemp}
    #     return JsonResponse(response)
    # except Message.DoesNotExist:
    #     response = {"result": "该用户不存在或者没有消息记录"}
    #     return JsonResponse(response)


# 发送信息
@login_required(login_url='/account/login/')
def request_for_message(request):
    messages = Message.objects.filter(toUser__username=request.user.username, is_received=False)
    response = []
    for message in messages:
        message_dict = {'from_user_name': message.fromUser.username, 'plaintext': message.plaintext,
                        'to_user_name': request.user.username, 'message_id': message.message_id,
                        'date': time.mktime(message.date.timetuple())}
        response.append(message_dict)
    return HttpResponse(json.dumps(response), status=200)


# 成功接收消息
@login_required(login_url='/account/login/')
def receive_successfully(request):
    if request.method == 'POST':
        data = request.POST
        try:
            message = Message.objects.filter(message_id=data['message_id']).get()
            message.is_received = True
            message.save()
            return HttpResponse(status=200)
        except Message.DoesNotExist:
            return HttpResponse(status=423)
    elif request.method == 'GET':
        if DEBUG:
            return render(request, 'receive_successfully.html')
    else:
        return HttpResponse(status=400)
