from .models import Post, Reply
from .forms import AddForm
from django.http import Http404
from django.shortcuts import render
from django.views import View

def index(request):
    posts = Post.objects.order_by("-pub_date")
    context = {
        "posts": posts
    }
    return render(request, "forum/index.html", context)

def details(request, post_id):
    try:
        post = Post.objects.get(pk=post_id)
        replies = Reply.objects.filter(post=post).order_by("-pub_date")
    except Post.DoesNotExist:
        raise Http404("Announcement does not exist!")
    context = {
        "post": post,
        "replies": replies
    }
    return render(request, "forum/detail.html", context)
        
class AddView(View):

    def get(self, request):
        form = AddForm()
        context = {'form' : form}
        return render(request, 'forum/add.html', context)

    def post(self, request):
        form = AddForm(request.POST)

        if form.is_valid():
            print(form.cleaned_data['post_title'])
            form.save()
            post = Post.objects.latest('id')
            replies = Reply.objects.filter(post=post).order_by("-pub_date")
        
        context = {
            "post": post,
            "replies": replies
        }
        return render(request, "forum/detail.html", context)
        
