package WebPAC::Input::Ovid;

use warnings;
use strict;

use lib 'lib';
use WebPAC::Input;
use base qw/WebPAC::Common/;

use Data::Dump qw/dump/;

=head1 NAME

WebPAC::Input::Ovid - support for Ovid citation export

=head1 VERSION

Version 0.01

=cut

our $VERSION = '0.01';

=head1 SYNOPSIS

Open file in Ovid citation export fromat

 my $input = new WebPAC::Input::Ovid(
	path => '/path/to/ovid-cites.txt',
 );

=head1 FUNCTIONS

=head2 new

Returns new low-level input API object

  my $input = new WebPAC::Input::Ovid(
  	path => '/path/to/ebsco.txt',
	filter => sub {
		my ($l,$field_nr) = @_;
		# do something with $l which is line of input file
		return $l;
	},
  }

Options:

=over 4

=item path

path to Ovid export file

=back

=cut

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

	my $arg = {@_};

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

	open( my $fh, '<', $arg->{path} ) || $log->logconfess("can't open $arg->{path}: $!");

	$log->info("reading '$arg->{path}'");

	my $rec;
	my $size = 0;
	my $tag;

	$self->{_rec} = [];

	while( my $line = <$fh> ) {
		$line =~ s{[\r\n]+$}{};
		next if $line eq '';

		warn "<< $line\n";

		if ( $line =~ m/^<(\d+)>$/ ) {
			my $expect_rec = $#{ $self->{_rec} } + 2;
			warn "wrong Ovid record number: $1 != $expect_rec" unless $1 == $expect_rec;
			push @{ $self->{_rec} }, $rec if $rec;
			warn "## rec = ",dump( $rec ),$/;
			$rec = { '000' => $1 };
		} elsif ( $line =~ /^(\w.+)/ ) {
			$tag = $1;
			warn "++ $tag\n";
		} elsif ( $line =~ /^\s\s(.+)/ ) {
			my $v = $1;
			$v =~ s{[\s\.]+$}{};
			$rec->{$tag} = $v;
		} else {
			warn "### skip: '$line'\n";
		}

	}

	# save last rec
	push @{ $self->{_rec} }, $rec if $rec;
	$self->{size} = $#{ $self->{_rec} } + 1;

	$log->debug("loaded ", $self->size, " records");

	$self ? return $self : return undef;
}

=head2 fetch_rec

Return record with ID C<$mfn> from database

  my $rec = $input->fetch_rec( $mfn, $filter_coderef );

=cut

sub fetch_rec {
	my $self = shift;

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

	return $self->{_rec}->[$mfn-1];
}


=head2 size

Return number of records in database

  my $size = $input->size;

=cut

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

=head1 AUTHOR

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

=head1 COPYRIGHT & LICENSE

Copyright 2008 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::Ovid
