package WebPAC::Input::Koha;

use warnings;
use strict;

use DBI;
use MARC::Fast;
use base qw/WebPAC::Common/;
use Carp qw/confess/;
use Data::Dump qw/dump/;

=head1 NAME

WebPAC::Input::Koha - read MARC records from Koha

=cut

our $VERSION = '0.01';

=head1 FUNCTIONS

=head2 new

  my $input = new WebPAC::Input::Koha(
  	dsn => '',
	filter => \&code_ref,
  }

=cut

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

	my $arg = {@_};

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

	if ( -e $arg->{path} ) {
		$log->info("Koha marc dump ", $arg->{path}, " exists");
		$self->{_koha_size} = 0;
	} else {

		$log->info("opening Koha database '$arg->{dsn}'");

		$self->{_dbh} = DBI->connect( $arg->{dsn}, $arg->{user}, $arg->{passwd}, { RaiseError => 1 } );
		$self->{_sth} = $self->{_dbh}->prepare( $arg->{sql} );
		$self->{_sth}->execute;
		$self->{_koha_size} = $self->{_sth}->rows;

		warn "got ", $self->{_koha_size}, " rows for ", $arg->{sql};

		open( $self->{_koha_fh}, '>', $arg->{path} ) || die "can't create $arg->{path}: $!";

	}

	$self ? return $self : return undef;
}

=head2 fetch_rec

Return record with ID C<$mfn> from database

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

=cut

sub fetch_rec {
	my $self = shift;

	my $mfn = shift;

	my $row = $self->{_sth}->fetchrow_hashref;

	if ( my $fh = $self->{_koha_fh} ) {
		if ( my $marc = $row->{marc} ) {
			print $fh $marc;
		} else {
			warn "MFN $mfn no marc in ",dump($row);
		}
	}

	push @{$row->{'000'}}, $mfn;
	return $row;
}

=head2 size

Return number of records in database

  my $size = $isis->size;

=cut

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


=head1 AUTHOR

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

=head1 COPYRIGHT & LICENSE

Copyright 2009 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;
