import datetime

from django.shortcuts import render, redirect
from django.core.paginator import Paginator

from books.models import Book
from datetime import datetime


def index(request):
    return redirect('books')


def book_view(request, date):
    template = 'books/book.html'
    date_cl = datetime.strptime(date, '%Y-%m-%d').date()
    data = list(Book.objects.values())

    date_up = list(Book.objects.filter(pub_date__gt=date_cl).values('pub_date'))
    date_down = list(Book.objects.filter(pub_date__lt=date_cl).values('pub_date'))

    date_up.append({'pub_date': ''})
    date_down.append({'pub_date': ''})

    context = {
        'books': [],
        'page': {'up': str(date_up[0]['pub_date']), 'down': str(date_down[0]['pub_date'])}
    }

    for i in data:
        if date_cl == i['pub_date']:
            context['books'].append(i)

    return render(request, template, context)


def books_view(request):
    template = 'books/books_list.html'
    data = list(Book.objects.values())
    context = {
        'books': data
    }
    return render(request, template, context)
