#wzc: 评论视图处理模块
from django.core.exceptions import ValidationError
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.views.generic.edit import FormView

from accounts.models import BlogUser
from blog.models import Article
from .forms import CommentForm
from .models import Comment


class CommentPostView(FormView):
    """wzc: 评论发表视图"""
    form_class = CommentForm
    template_name = 'blog/article_detail.html'

    @method_decorator(csrf_protect)
    def dispatch(self, *args, **kwargs):
        """wzc: CSRF保护装饰器"""
        return super(CommentPostView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        """wzc: GET请求重定向到文章详情页"""
        article_id = self.kwargs['article_id']
        article = get_object_or_404(Article, pk=article_id)
        url = article.get_absolute_url()
        return HttpResponseRedirect(url + "#comments")

    def form_invalid(self, form):
        """wzc: 表单验证失败处理"""
        article_id = self.kwargs['article_id']
        article = get_object_or_404(Article, pk=article_id)
        return self.render_to_response({
            'form': form,
            'article': article
        })

    def form_valid(self, form):
        """wzc: 表单验证成功后的评论保存逻辑"""
        user = self.request.user
        #wzc: 获取评论作者信息
        author = BlogUser.objects.get(pk=user.pk)
        article_id = self.kwargs['article_id']
        article = get_object_or_404(Article, pk=article_id)

        #wzc: 检查文章是否允许评论
        if article.comment_status == 'c' or article.status == 'c':
            raise ValidationError("该文章评论已关闭.")

        #wzc: 创建评论对象
        comment = form.save(commit=False)
        comment.article = article
        comment.author = author

        #wzc: 根据博客设置决定是否自动启用评论
        from djangoblog.utils import get_blog_setting
        settings = get_blog_setting()
        if not settings.comment_need_review:
            comment.is_enable = True

        #wzc: 处理父评论
        parent_comment_id = form.cleaned_data.get('parent_comment_id')
        if parent_comment_id:
            try:
                parent_comment = Comment.objects.get(pk=parent_comment_id)
                comment.parent_comment = parent_comment
            except Comment.DoesNotExist:
                #wzc: 父评论不存在时忽略，不中断流程
                pass

        comment.save()

        #wzc: 重定向到文章详情页的评论区域
        return HttpResponseRedirect(
            "%s#div-comment-%d" % (article.get_absolute_url(), comment.pk))