#!/usr/bin/env Python
# coding=utf-8

from .models import Category, Post
from django.shortcuts import render, get_object_or_404
from django.db.models import Q, F
from django.core.paginator import Paginator


# 主页Home
def index(request):
    post_list = Post.objects.all()
    paginator = Paginator(post_list, 2)
    page_number = request.GET.get('page')
    page_object = paginator.get_page(page_number)
    return render(request, 'passage/index.html', {
        'page_object': page_object
    })


# 按照分类获取文章
def category_list(request, category_id):
    category = get_object_or_404(Category, id=category_id)
    posts = category.post_set.all()
    paginator = Paginator(posts, 2)
    page_number = request.GET.get('page')
    page_object = paginator.get_page(page_number)
    return render(request, 'passage/list.html', {
        'category': category,
        'page_object': page_object
    })


# 通过文章id获取文章正文
def post_detail(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    prev_post = Post.objects.filter(id__lt=post_id).last()
    next_post = Post.objects.filter(id__lt=post_id).first()
    Post.objects.filter(id=post_id).update(pv=F('pv') + 1)
    return render(request, 'passage/detail.html', {
        'post': post,
        'prev_post': prev_post,
        'next_post': next_post
    })


# 通过标题/描述/正文来检索文章
def search(request):
    keyword = request.GET.get('keyword')
    if not keyword:
        post_list = Post.objects.all()
    else:
        post_list = Post.objects.filter(Q(title__icontains=keyword) |
                                        Q(desc__icontains=keyword) |
                                        Q(content__icontains=keyword))
    paginator = Paginator(post_list, 2)
    page_number = request.GET.get('page')
    page_object = paginator.get_page(page_number)
    return render(request, 'passage/index.html', {
        'page_object': page_object
    })


# 文章归档列表页
def archives(request, year, month):
    post_list = Post.objects.filter(add_date__year=year, add_date__month=month)
    paginator = Paginator(post_list, 2)
    page_number = request.GET.get('page')
    page_object = paginator.get_page(page_number)
    return render(request, 'passage/archives_list.html', {
        'page_obj': page_object,
        'year': year,
        'month': month
    })
