package WebPAC::Input::CSV;

use warnings;
use strict;

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

use Text::CSV;
use Encode;
use Data::Dump qw/dump/;

=head1 NAME

WebPAC::Input::CSV - support for CSV Export Format

=cut

our $VERSION = '0.02';

=head1 FUNCTIONS

=head2 new

Returns new low-level input API object

  my $input = new WebPAC::Input::CSV(
  	path => '/path/to/records.csv',
	header_first => 1,
  );

Options:

=over 4

=item path

path to CSV file

=back

Default encoding of input file is C<utf-8>

C<header_first> will use first line as header names.

=cut

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

	my $arg = {@_};

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

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

	my $csv = Text::CSV->new({ binary => 1 });

	$self->{size} = 0;

	if ( $self->{header_first} ) {
		my $line = $csv->getline( $fh );
		$self->{header_names} = $line;
		$self->debug( "header_names = ",dump( $self->{header_names} ) );
	}

	while ( 1 ) {
		my $line = $csv->getline( $fh );
		last if $csv->eof;

		$log->logdie( "can't parse CSV file ", $csv->error_diag ) unless $line;

		my $rec;
		$rec->{'000'} = [ ++$self->{size} ];

		my $col = 'A';
		my $header_pos = 0;

		foreach my $cell ( @$line ) {
			my $str = eval { Encode::decode_utf8( $cell ) };
			if ( $@ ) {
				if ( $@ =~ m/Cannot decode string with wide characters/ ) {
					$str = $cell;
				} else {
					die "ERROR: $@ in line ",dump( $line );
				}
			} else {
				utf8::upgrade( $cell );
				$str = $cell;
			}
				
			$rec->{ $col++ } = $str;

			if ( $self->{header_names} ) {
				$rec->{ $self->{header_names}->[$header_pos] } = $str;
				$header_pos++;
			}
		}

		push @{ $self->{_rec} }, $rec;

	};

	$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, $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 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; # End of WebPAC::Input::CSV
