from django.shortcuts import redirect
from django.views import generic
from django.urls import reverse
from django.contrib.auth.mixins import LoginRequiredMixin

from webapp.models import Comment
from webapp.forms import CommentForm


class CommentCreateView(LoginRequiredMixin, generic.CreateView):
    model = Comment
    template_name = 'comments/comment.html'
    form_class = CommentForm

    def form_valid(self, form):
        # article = get_object_or_404(Article, id=self.kwargs.get(''))
        article_id = self.kwargs.get('article_id')

        comment = form.save(commit=False)
        comment.article_id = article_id
        comment.author = self.request.user
        comment.save()

        return redirect('articles_detail', id=article_id)


class CommentUpdateView(generic.UpdateView):
    model = Comment
    template_name = 'comments/comment.html'
    form_class = CommentForm
    context_object_name = 'comment'
    pk_url_kwarg = 'comment_id'

    def get_success_url(self):
        return reverse('articles_detail', kwargs={'id': self.object.article.id})


class CommentDeleteView(generic.DeleteView):
    model = Comment
    pk_url_kwarg = 'comment_id'
    
    def get_success_url(self):
        return reverse('articles_detail', kwargs={'id': self.object.article.id})
