use strict;
use warnings;
use feature ':5.10';

package Liberl::View::Books;
use Jifty::View::Declare -base;

# aliased in /books

template '/list' => sub {
    my $books = get('books');
    div {
        dl {
            while (my $book = $books->next()) {
                my $id = $book->id;

                render_region(
                    name => "book_$id",
                    path => '/book/show/preview',
                    arguments => { id => $id },
                    );
            }
        }
    }
};

template '/last' => page {
    { title is _('Last books') }

    my $count = get('count') // 10;

    render_region(
        name => 'books_last',
        path => '/books/last/widget',
        arguments => { count => $count },
        );
};

template '/last/widget' => sub {
    my $last = get('count');

    my $books = Liberl::Model::BookCollection->new();
    $books->unlimit;
    $books->order_by(
        column => 'created_on',
        order => 'DESC',
        );
    $books->set_page_info(current_page => 1,
                          per_page     => $last,
        );

    div {
        dl {
            while (my $book = $books->next()) {
                my $id = $book->id;

                render_region(
                    name => "book_$id",
                    path => '/book/show/preview',
                    arguments => { id => $id },
                    );
            }
        }
    }
};

template '/recent' => page {
    { title is _('Recent books') }

    my $days = get('days') // 10;

    render_region(
        name => 'books_recent',
        path => '/books/recent/widget',
        arguments => { days => $days },
        );
};

template '/recent/widget' => sub {
    my $days = get('days');

    my $dt = DateTime->now;
    my $d = DateTime::Duration->new(days => $days);
    my $dt_min = $dt - $d;

    my $books = Liberl::Model::BookCollection->new();
    $books->limit(
        column   => 'created_on',
        operator => '>=',
        value    => $dt_min,
        );
    $books->order_by(
        column => 'created_on',
        order => 'DESC',
        );

    div {
        dl {
            while (my $book = $books->next()) {
                my $id = $book->id;

                render_region(
                    name => "book_$id",
                    path => '/book/show/preview',
                    arguments => { id => $id },
                    );
            }
        }
    }
};

template '/all' => page {
    { title is _('All books') }

    my $books = Liberl::Model::BookCollection->new();
    $books->unlimit();

    div {
        dl {
            while (my $book = $books->next()) {
                my $id = $book->id;

                render_region(
                    name => "book_$id",
                    path => '/book/show/preview',
                    arguments => { id => $id, },
                    );
            }
        };
    }
};

1;

