package WebPAC::Input::MARC;

use warnings;
use strict;

use MARC::Fast 0.12;
use base qw/WebPAC::Common/;
use Carp qw/confess/;

=head1 NAME

WebPAC::Input::MARC - support for MARC database files

=head1 VERSION

Version 0.09

=cut

our $VERSION = '0.09';


=head1 SYNOPSIS

Open USMARC, Unimarc or any other file format that has same internal
structure using C<MARC::Fast>.

 my $marc = new WebPAC::Input::MARC(
	path => '/path/to/marc.iso'
 );

=head1 FUNCTIONS

=head2 new

Returns new low-level input API object

  my $marc = new WebPAC::Input::MARC(
  	path => '/path/to/marc.iso',
  }

=cut

sub new {
	my $class = shift;
	my $self = {@_};
	bless($self, $class);

	my $arg = {@_};

	my $log = $self->_get_logger();

	$log->info("opening MARC database '$arg->{path}'");

	die "no filter support any more!" if $arg->{filter};

	my $db = new MARC::Fast(
		marcdb => $arg->{path},
	);
	my $db_size = $db->count - 1;	# FIXME

	$self->{_marc_size} = $db_size;
	$self->{_marc_db} = $db;

	$self ? return $self : return undef;
}

=head2 fetch_rec

Return record with ID C<$mfn> from database

  my $rec = $self->fetch_rec( $mfn );

=cut

sub fetch_rec {
	my $self = shift;

	my ($mfn, $filter_coderef) = @_;

	if ($mfn > $self->{_marc_size}) {
		$self->_get_logger()->warn("seek beyond database size $self->{_marc_size} to $mfn");
	} else {
		my $marc = $self->{_marc_db} || confess "no _marc_db?";
		my $row = $marc->to_hash($mfn, include_subfields => 1, hash_filter => $filter_coderef);
		push @{$row->{'000'}}, $mfn;
		push @{$row->{'leader'}}, $marc->last_leader;
		return $row;
	}
}

=head2 dump_ascii

Return ASCII dump of record with ID C<$mfn> from database

  print $self->dump_ascii( $mfn );

=cut

sub dump_ascii {
	my $self = shift;

	my $mfn = shift;
	return $self->{_marc_db}->to_ascii($mfn);
}

=head2 size

Return number of records in database

  my $size = $isis->size;

=cut

sub size {
	my $self = shift;
	return $self->{_marc_size};
}


=head1 AUTHOR

Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>

=head1 COPYRIGHT & LICENSE

Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

1; # End of WebPAC::Input::MARC
