from django.shortcuts import redirect
from django.contrib.contenttypes.models import ContentType
from django.contrib import messages
from ..models import Comment


def comment_add(request):
    if request.method == 'POST':
        content_type_id = request.POST.get('content_type')
        object_id = request.POST.get('object_id')
        content = request.POST.get('content')
        parent_id = request.POST.get('parent')

        try:
            content_type = ContentType.objects.get(id=content_type_id)
            target = content_type.get_object_for_this_type(id=object_id)
        except Exception as e:
            messages.error(request, '无效的评论目标')
            return redirect('/')

        comment = Comment(content_type=content_type,
                          object_id=object_id,
                          content=content,
                          user=request.user)

        if parent_id:
            try:
                parent = Comment.objects.get(id=parent_id)
                comment.parent = parent
            except Comment.DoesNotExist:
                pass

        comment.save()
        messages.success(request, '评论已提交')
        return redirect(target.get_absolute_url() + '#comment-' +
                        str(comment.id))

    return redirect('/')
