from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.generic import ListView
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from social import models, forms
from django.db.models import Q
from django.views.generic.detail import SingleObjectMixin

# Create your views here.


class Wall(LoginRequiredMixin, ListView):
    #queryset = models.Post.objects.all()
    template_name = "social/wall.html"
    context_object_name = "posts"
    login_url = "auth/login"

    def get_queryset(self):
        friendIds = [friend.person2.id for friend in models.Friends.objects.filter(
            person1=self.request.user)]
        friendIds = friendIds + \
            [friend.person1.id for friend in models.Friends.objects.filter(
                person2=self.request.user)]
        # for reverse order use "-created_at"
        return models.Post.objects.filter(user__in=friendIds).order_by("-created_at")


class Home(LoginRequiredMixin, ListView):

    template_name = "social/home.html"
    context_object_name = "posts"
    login_url = "auth/login"

    def get_queryset(self):
        return models.Post.objects.filter(
            Q(user=self.request.user)
        ).order_by("-created_at")

    def get_context_data(self, *args, **kwargs):
        data = super().get_context_data(*args, **kwargs)
        data['post_form'] = forms.PostForm()
        return data


class Post(LoginRequiredMixin, View):
    def post(self, request):
        form = forms.PostForm(request.POST, request.FILES)
        if form.is_valid():
            # creating django like model without saving to database
            post = form.save(commit=False)
            post.user = request.user
            post.save()
        return redirect('/home/')


# q in django query
# Single Object Mixin provides a mechanism for looking up an object associated with the current HTTP request
class PostLike(View):
    model = models.Post

    def post(self, request, pk):  # pk as kwargs because keyword argument pk taken in urls.py
        post = self.model.objects.get(pk=pk)
        print(post)
        number = models.Like.objects.filter(post=post, user=request.user)
        if not number:
            models.Like.objects.create(post=post, user=request.user)
        return HttpResponse(code=204)

# sendgrid mail django


class PostComment(View):
    model = models.Post
    form = forms.PostComment

    def post(self, request, pk):  # pk as kwargs because keyword argument pk taken in urls.py
        post = self.model.objects.get(pk=pk)
        form = self.form(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.user = request.user
            comment.save()
            return HttpResponse(code=204)
        return HttpResponse(code=400)
