#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package Common::Parser::Iterator::Excel;

use Data::Dumper;

#
# Common::Parser::Iterator::Excel
#
# This iterator is used to parse Excel 97/2000 spreedsheets.
# This files assumes that the data is on the first worksheet
# of the workbook.
#

use strict;

use lib '/app/tools/common/lib';

use Common::Assert;
use Common::Log;

use base 'Common::Parser::Iterator';

sub currentRow { shift->{_currentRow} }
sub lastRow    { shift->{_lastRow} }
sub excel      { shift->{_excel} }

sub rewind {
    my $self = shift;
    my $sheet;

    eval { $sheet = $self->{_excel}->Worksheet(0); };

    if ($@) {
        Common::Log::Debug( Dumper( $self->excel ) );
        Common::Log::Print("Read Error: $@");

        #die $@;
    }

    $self->{_currentRow} = undef;
    $self->{_lastRow}    = undef;

    return unless ($sheet);

    my ( $rowMin, $rowMax ) = $sheet->row_range();

    $self->{_currentRow} = $rowMin;
    $self->{_lastRow}    = $rowMax + 1;
}

sub hasNext {
    my $self = shift;

    return unless ( defined( $self->{_lastRow} ) && defined( $self->{_currentRow} ) );

    return $self->{_currentRow} < $self->{_lastRow};
}

sub next {
    my $self = shift;

    return unless ( $self->hasNext() );

    my @row = $self->_fetchRow();

    $self->{_currentRow} += 1;

    my $dataClass = $self->_itemClass();
    eval "require $dataClass";

    return $dataClass->new( row => \@row );
}

sub rowCount {
    shift->{_lastRow};
}

###
1;    # Play nicely.
###
