from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.views import View

from articles.forms import CommentForm
from articles.helpers.views import CreateView, UpdateView
from articles.models import Comment, Article


class CommentCreateView(CreateView):
    model = Comment
    form_class = CommentForm
    template_name = 'articles/create.html'

    def form_valid(self, form):
        article = get_object_or_404(Article, pk=self.kwargs.get('pk'))
        form.instance.article = article
        form.instance.author = self.request.user
        return super().form_valid(form)

    def get_redirect_url(self):
        return reverse('article_detail', kwargs={'pk': self.object.article.pk})


class CommentDetailView(View):
    def post(self, request, *args, **kwargs):
        form = CommentForm(request.POST)
        article_pk = kwargs.get('article_pk')
        if form.is_valid():
            article = get_object_or_404(Article, pk=article_pk)
            article.comments.create(
                text=request.POST.get("text"),
                author=request.POST.get("author")
            )

        return redirect('article_detail', article_pk)


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

    def get_redirect_url(self):
        return reverse('article_detail', kwargs={
            'pk': self.object.article.pk
        })
