package WebPAC::Output::Excel;

use warnings;
use strict;

use WebPAC::Common;
use base qw/WebPAC::Common WebPAC::Output Class::Accessor/;
__PACKAGE__->mk_accessors(qw(
path
filter

workbook
worksheet
line
));

use Spreadsheet::WriteExcel;
use File::Slurp;
use Encode qw/decode/;

=head1 NAME

WebPAC::Output::Excel - Create binary Excel file

=cut

=head1 SYNOPSIS

Create Excel output for export into other systems from C<csv()> constructs
with columns named C<A>..C<Z> (or whatever L<Spreadsheet::WriteExcel> supports)

=head1 FUNCTIONS

=head2 new

 my $out = new WebPAC::Output::Excel({
 	path => '/path/to/file.xls',
	filter => 'csv',
 });

Options are:

=over 4

=item path

path to Excel file

=item filter

select name of variable from C<< to('csv','A',...) >> constructs used by
L<WebPAC::Normalize>

=back

=head2 init

  $out->init;

=cut

sub init {
	my $self = shift;
	my $log = $self->_get_logger;

	if ( ! $self->path ) {
		$log->logwarn("need path for ", __PACKAGE__);
		return 0;
	}

	$self->workbook( Spreadsheet::WriteExcel->new( $self->path ) ) ||
		$log->logdie("can't open ", $self->path,": $!");

	$self->worksheet( $self->workbook->add_worksheet() ) ||
		$log->logdie("can't add_worksheet");

	$self->line( 1 );

	$self->filter( 'csv' ) unless $self->filter;

	return 1;
}


=head2 add

Adds one entry to database.

  $out->add( 42, $ds );

Returns number of columns added

=cut

sub add {
	my $self = shift;

	my ( $id, $ds ) = @_;

	my $log = $self->_get_logger;
	$log->logdie("need id") unless defined $id;
	$log->logdie("need ds") unless $ds;

	$log->debug("id: $id ds = ",sub { dump($ds) });

	my $l = $self->line;

	my $cols = 0;

	my $hash = $self->ds_to_hash( $ds, $self->filter, disable_key_mungle => 1, single_values => 1 );
	$log->debug("hash from ",$self->filter," = ", sub { dump( $hash ) });

	my $worksheet = $self->worksheet || $log->logconfess("no worksheet?");
	foreach my $col ( sort grep { /^[A-Z]/ } keys %$hash ) {
		# FIXME internal WebPAC encoding is ISO-8859-2
		my $val = decode('ISO-8859-2', $hash->{$col});
		# protect data which looks like forula
		$val = "'$val" if $val =~ m/^=/;
		$log->debug("$col$l|$val");
		$worksheet->write( $col . $l , $val );
		$cols++;
	}

	$self->line( $l + 1 ) if $cols;

	return $cols;
}

=head2 finish

 $out->finish;

=cut

sub finish {
	my $self = shift;

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

	my $path = $self->path;

	$self->workbook->close() ||
		$log->logdie("can't close Excel file $path: $!");

	$log->info("created $path ", -s $path, " bytes with ", $self->line, " rows");

	return $self->line;
}

=head1 AUTHOR

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

=head1 COPYRIGHT & LICENSE

Copyright 2007 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::Output::Excel
