#!/usr/bin/perl -w

use strict;

use Cwd qw/abs_path/;
use File::Temp qw/tempdir/;
use Data::Dumper;
use lib './lib';

use WebPAC::Lookup;
use WebPAC::Input::ISIS;
use WebPAC::DB;
use WebPAC::Normalize::XML;
use WebPAC::Output::TT;
use WebPAC::Output::Estraier;

my $abs_path = abs_path($0);
$abs_path =~ s#/[^/]*$#/#;

my $isis_file = '/data/isis_data/ps/LIBRI/LIBRI';

my $lookup = new WebPAC::Lookup(
	lookup_file => "$abs_path/conf/lookup/isis.pm",
);

my $isis = new WebPAC::Input::ISIS(
	code_page => 'ISO-8859-2',	# application encoding
	limit_mfn => 50,
);

my $maxmfn = $isis->open(
	filename => $isis_file,
	code_page => '852',		# database encoding
);

my $path = './db/';

my $db = new WebPAC::DB(
	path => $path,
);

my $n = new WebPAC::Normalize::XML(
#	filter => { 'foo' => sub { shift } },
	db => $db,
	lookup_regex => $lookup->regex,
	lookup => $lookup,
);

$n->open(
	tag => 'isis',
	xml_file => "$abs_path/conf/normalize/isis_ffzg.xml",
);

my $out = new WebPAC::Output::TT(
	include_path => "$abs_path/conf/output/tt",
	filters => { foo => sub { shift } },
);

my $est = new WebPAC::Output::Estraier(
	url => 'http://localhost:1978/node/webpac2',
	user => 'admin',
	passwd => 'admin',
	database => 'ps',
);

while (my $row = $isis->fetch) {

	my $mfn = $row->{'000'}->[0] || die "can't find MFN";

	my $ds = $n->data_structure($row);

#	print STDERR Dumper($row, $ds);

	my $html = $out->apply(
		template => 'html_ffzg.tt',
		data => $ds,
	);

	# create test output

	my $file = sprintf('out/%02d.html', $mfn );
	open(my $fh, '>', $file) or die "can't open $file: $!";
	print $fh $html;
	close($fh);

	$html =~ s#\s*[\n\r]+\s*##gs;

#	print STDERR $html;

	$est->add(
		id => $mfn,
		ds => $ds,
		type => 'search',
	);

};
