use strict;
use warnings;

package Liberl::Dispatcher;
use Jifty::Dispatcher -base;

before '/add' => run {
    unless(Jifty->web->current_user->id) {
        Jifty->web->tangent(url => '/login');
    }
};

before '/add/book' => run {
    my $libraries = Liberl::Model::LibraryCollection->new();
    $libraries->unlimit();
    warn '/add/book';
    unless($libraries->count) {
        Jifty->web->tangent(url => '/add/library');
    }
};

before qr{/add/(library/format)} => run {
    set 'next' => Jifty->web->request->continuation ||
        Jifty::Continuation->new( request => Jifty::Request->new(path => "/add/$1"));
}

before '/manage' => run {
    unless(Jifty->web->current_user->id) {
        Jifty->web->tangent(url => '/login');
    }
};

on "/show/*" =>
    run {
        set id => $1;
        show '/book/show';
};

on "/last/*" =>
    run {
        set count => $1;
        show '/books/last';
};

on "/recent/*" =>
    run {
        set days => $1;
        show '/books/recent';
};

before '*' => run {
    Jifty->web->navigation->child(
        All        => label => _('All books') =>
        url        => '/books/all',
        sort_order => '600'
        );
    Jifty->web->navigation->child(
        Recent     => label => _('Recent books') =>
        url        => '/books/recent',
        sort_order => '610'
        );
    Jifty->web->navigation->child(
        Last       => label => _('Last books') =>
        url        => '/books/last',
        sort_order => '620'
        );
    if (Jifty->web->current_user->id) {
        Jifty->web->navigation->child(
            AddBook    => label => _('Add book') =>
            url        => '/add/book',
            sort_order => '700'
            );
        Jifty->web->navigation->child(
            AddLibrary => label => _('Management') =>
            url        => '/manage',
            sort_order => '800'
            );
    }
};

on '/add/book/form/isbn' => run {
    my $search = Jifty->web->response->result('add_isbn');

    set(search => $search);
};

on 'search', run {
    my $search = Jifty->web->response->result('search');
    my $collection = undef;
    if($search) {
        $collection = $search->content('search');
    }   
    my $action =  Jifty->web->new_action(class => 'SearchBook', moniker => 'search');
    $action->sticky_on_success(1);

    set search => $action;
    set books => $collection;
};

1;

