from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from notifications.signals import notify
from article.models import ArticlePost
from .forms import CommentPost
from .models import Comment


@login_required(login_url='/user/login')
def post_comment(request, article_id, parent_comment_id=None):
    article = get_object_or_404(ArticlePost, id=article_id)
    if request.method == 'POST':
        comment_form = CommentPost(data=request.POST)
        if comment_form.is_valid():
            new_comment_form = comment_form.save(commit=False)
            new_comment_form.article = article
            new_comment_form.user = request.user
            # 二级回复
            if parent_comment_id:
                parent_comment = Comment.objects.get(id=parent_comment_id)
                # 若回复层级超过二级，则转换为二级
                new_comment_form.parent_id = parent_comment.get_root().id
                # 被回复人
                new_comment_form.reply_to = parent_comment.user
                new_comment_form.save()
                if not parent_comment.user.is_superuser:
                    notify.send(
                        request.user,
                        recipient=parent_comment.user,
                        verb='回复了你',
                        target=article,
                        action_object=new_comment_form,
                    )
                return HttpResponse('200 OK')
            new_comment_form.save()
            # 给管理员发送通知
            if not request.user.is_superuser:
                notify.send(
                    request.user,
                    recipient=User.objects.filter(is_superuser=1),
                    verb='回复了你',
                    target=article,
                    action_object=new_comment_form,
                )
            return redirect(article)
        else:
            return HttpResponse('表单有错误，请重新填写')
    elif request.method == 'GET':
        comment_form = CommentPost()
        context = {
            'comment_form': comment_form,
            'article_id': article_id,
            'parent_comment_id': parent_comment_id
        }
        return render(request, 'comment/reply.html', context)
    else:
        return HttpResponse('发表评论仅接受GET/POST请求')
