from django.shortcuts import render
from django.http import HttpResponse
from .models import *
from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin
# Create your views here.


def home(request):
    context= {
    'posts':Post.objects.all()
    }
    return render(request,'blog/home.html',context)

###class based views
class PostListView(ListView):
    ##use a model to list all data
    model = Post
    template_name = 'blog/home.html' # <app>/<model>_<viewtype>/html
    context_object_name = 'posts'
    ordering = ['date_posted'] ### - will sort by ascending
    paginate_by = 4

###Individual posts detail view
class UserPostListView(ListView):
    ##use a model to list all data
    model = Post
    template_name = 'blog/home.html' # <app>/<model>_<viewtype>/html
    context_object_name = 'posts'
    ordering = ['date_posted'] ### - will sort by ascending
    paginate_by = 4


class PostDetailView(DetailView):
    ##use a model to list all data
    model = Post

class PostCreateView(CreateView):
    model = Post
    fields = ['title','content']

    def form_valid(self,form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
    model = Post
    fields = ['title','content']

    def form_valid(self,form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class PostDeleteView(LoginRequiredMixin,UserPassesTestMixin,DeleteView):
    ##use a model to list all data
    model = Post
    success_url = '/'
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False



def about(request):
    return render(request,'blog/about.html')
