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.03';

=head1 FUNCTIONS

=head2 new

  my $input = new WebPAC::Input::Koha(
  	dsn    => $ENV{KOHA_DSN}, # 'dbi:mysql:database=koha;host=koha.example.com',
	user   => $ENV{KOHA_USER},
	passwd => $ENV{KOHA_PASSWD},
  }

=cut

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

	my $arg = {@_};

	my $log = $self->_get_logger();
	$log->debug( 'arg = ', dump($arg) );

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

		$arg->{dsn}    ||= $ENV{KOHA_DSN};
		$arg->{user}   ||= $ENV{KOHA_USER};
		$arg->{passwd} ||= $ENV{KOHA_PASSWD};
		$arg->{sql}    ||= 'select biblionumber, marc from biblioitems order by biblionumber asc';
		$arg->{sql}    .= ' limit ' . $arg->{limit} if $arg->{limit};
		$arg->{sql}    .= ' offset ' . $arg->{offset} if $arg->{offset};

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

		$self->{_dbh} = DBI->connect( $arg->{dsn}, $arg->{user}, $arg->{passwd}, {
			RaiseError => 1,
			#mysql_enable_utf8 => 1, # not really needed
		} );
		$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;

	sub _error {
		my ( $mfn, $error, $row ) = @_;
		$self->_get_logger()->error( "MFN $mfn $error ", dump($row) );
	}

	if ( my $fh = $self->{_koha_fh} ) {
		if ( my $marc = $row->{marc} ) {
			if ( length($marc) != substr( $marc, 0, 5 ) ) {
				_error $mfn => "wrong length " . length($marc), $row;
			} elsif ( $marc !~ /\x1E\x1D$/ ) {
				_error $mfn => "wrong end", $row;
			} else {
				print $fh $marc;
			}
		} else {
			_error $mfn => "no marc",$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} + $self->{offset};
}


=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;
