from urllib.parse import urlencode
from django.http.response import HttpResponse as HttpResponse
from django.contrib import messages
from django.views import generic
from django.db.models import Q

from webapp.forms import SearchForm
from webapp.models import Article
from webapp.views.articles import (
    ArticleCreateView, 
    ArticleDetailView, 
    ArticleUpdateView, 
    ArticleDeleteView,
)
from webapp.views.comments import (
    CommentCreateView,
    CommentUpdateView,
    CommentDeleteView,
)


class IndexRedirectView(generic.RedirectView):
    pattern_name = 'index'


class IndexListView(generic.ListView):
    template_name = 'index.html'
    context_object_name = 'articles'
    model = Article
    ordering = ['-created_at']
    paginate_by = 5
    paginate_orphans = 1
    
    def get(self, request, *args, **kwargs):
        self.form = SearchForm(self.request.GET)
        self.search_value = None

        if self.form.is_valid():
            self.search_value = self.form.cleaned_data['search']

        return super().get(request, *args, **kwargs)

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=None, **kwargs)
        context['form'] = self.form
        
        if self.search_value:
            context['query_params'] = urlencode({'search': self.search_value})
        
        # DEBUG - Отладка
        # INFO - Информационное
        # SUCCESS - Успех
        # WARNING - Предупреждение
        # ERROR - Ошибка

        messages.add_message(self.request, messages.SUCCESS, 'Вы молодец!')

        # list comp
        self.request.session['index:messages'] = [vars(m) for m in self.request._messages]

        res = []
        for m in self.request._messages:
            res.append(vars(m)['message'])

        return context
    
    def get_queryset(self):
        qs = super().get_queryset()
        
        if self.search_value:
            query = (
                Q(title__icontains=self.search_value) 
                | Q(author__icontains=self.search_value)
            )
            qs = qs.filter(query).distinct()

        return qs
