#POSTS VIEWS.PY
from django.shortcuts import render
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin

from django.http import Http404
from django.views.generic import CreateView,ListView,DetailView,DeleteView
from django.contrib import messages

from braces.views import SelectRelatedMixin

from posts.models import Post
from posts import forms

from django.contrib.auth import get_user_model
User = get_user_model()

class PostList(SelectRelatedMixin,ListView):
    model = Post
    select_related = ('user','group')

class UserPosts(ListView):
    model = Post
    template_name = 'posts/user_post_list.html'

    def get_queryset(self): #it is to check if the user exists with the username
        try:
            self.post_user = User.objects.prefetch_related('posts').get(username__iexact=self.kwargs.get('username'))
        except User.DoesNotExit:
            raise Http404
        else:
            return self.post_user.posts.all()

    def get_context_data(self,**kwargs):
        context = super().get_context_data(**kwargs)
        context['post_user'] = self.post_user
        return context

class PostDetail(SelectRelatedMixin,DetailView):
    model = Post
    select_related = ('user', 'group')


    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user__username__iexact=self.kwargs.get('username'))


class CreatePost(LoginRequiredMixin,SelectRelatedMixin,CreateView):
    model = Post
    fields = ('message','group')

    def form_valid(self,form):#to connect the actual post to the user itself
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)

class DeletePost(LoginRequiredMixin,SelectRelatedMixin,DeleteView):
    model = Post
    select_related = ('user','group')
    success_url = reverse_lazy('posts:all')

    def get_queryset(self):
        queryset =super().get_queryset()
        return queryset.filter(user_id=self.request.user.id)

    def delete(self,*args,**kwargs):
        messages.success(self.request,'Post Deleted')
        return super().delete(*args,**kwargs)
