# -*- cperl -*-
# -----------------------------------------------------------------------------
# $Id: List.pm,v 1.4 2004/12/11 05:41:53 admin Exp $
# -----------------------------------------------------------------------------
package Celaenito::Httpd::List;
use strict;
use warnings;
use HTTP::Status;
use URI::QueryParam;
use Template;
use Celaenito::DB;
use Celaenito::Template;
use Celaenito::Permission;
use Celaenito::StaticFile;
use Celaenito::Config;
use Celaenito::Curi;
use Celaenito::FileStorage;
use Celaenito::Httpd;
use Pager;
use Kibibyte qw(kibibyte_format);

sub handler {
    my ($req, $resp) = @_;

    not CAN_SEE($req) and
      return need_auth_handler(@_);

    my $t = $req->uri->query_form_hash;

    my @where;
    if ($_ = $req->uri->query_param('url')) {
	s/%/%%/g;
	s/_/%_/g;
	push @where, sprintf 'url LIKE %s', DB->quote('%'.$_.'%');
    }
    if ($_ = $req->uri->query_param('label')) {
	s/%/%%/g;
	s/_/%_/g;
	push @where, sprintf 'label LIKE %s', DB->quote('%'.$_.'%');
    }
    if (!$req->uri->query_param('show_labelless')) {
	push @where, sprintf 'label IS NOT NULL';
    }
    my $where = @where ?
      'WHERE '.join(' AND ', @where) : '';

    my $pager = Pager->new(
	fetch => {
	    sql => qq{
		SELECT *
		  FROM target_url
                $where
                 ORDER BY last_modified DESC
            },
	    dbh => DB,
	},
	page_to_show   => scalar($req->uri->query_param('page')) || 1,
	pagenums_limit => 10,
	items_per_page => scalar($req->uri->query_param('limit')) || 20,
	show_meta => sub {
	    my %meta = @_;
	    $t->{list} = {
		page      => $meta{page},
		last_page => $meta{last_page},
		pages     => [$meta{pagelink_begin} .. $meta{pagelink_end}],
		entries   => [],
	    };
	},
	show_content => sub {
	    my $row = shift;

	    my $ent = {};
	    push @{$t->{list}{entries}}, $ent;

	    $ent->{celaenito_url} =
	      celaenito_uri(
		  host_uri => $req->uri,
		  orig_uri => $row->{url},
		  time     => 'latest')
		->as_string;
	    $ent->{original_url} = $row->{url};
	    $ent->{label}        = $row->{label} || '';
	    $ent->{versions}     = do {
		scalar FS->versions_list($row->{urlid});
	    };
	    $ent->{size}         = do {
		my $size = 0;
		foreach my $ver (FS->versions_list($row->{urlid})) {
		    $size += FS->get_size($row->{urlid}, $ver);
		}
		kibibyte_format '%.2f %s', $size;
	    };
	    $ent->{urlid}        = $row->{urlid};
	},
       );
    $pager->execute;

    $t->{title} = config('ui.title');
    
    my $out;
    TMPL->process('list.tt', $t, \$out)
      or die Template->error;
    
    $resp->content($out);
    return RC_OK;
}

1;
