#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------

package Common::Parser::Iterator::Excel::XLS;

#
# Common::Parser::Iterator::Excel::XLS
#
# 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::Log;
use Common::RSApp;
use Common::Assert;
use Common::UTF8;
use Data::Dumper;

use Unicode::String;
use Unicode::Map8;

use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::Utility qw(ExcelFmt);

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

sub CanParse {
    my $class = shift;
    my %args  = @_;
    my $self  = {};
    bless $self, $class;

    assert( $args{filename}, "Filename Required" );

    if ( $args{filename} =~ /\.xls$/ ) {
        return $self;
    }

    return;
}

sub open {
    my $self = shift;
    my $filename = shift || $self->{_filename};
    my $format;

    $self->{_error}    = undef;
    $self->{_filename} = $filename;

    assert( $filename,    "File required" );
    assert( -r $filename, "Can not read file: $filename" );

    Common::Log::Debug("Opening Excel Spreadsheet: $filename");

    eval {
        $self->{_excel} = Spreadsheet::ParseExcel::Workbook->Parse($filename);

        if ( $self->excel ) {
            $self->rewind();
        } else {
            $self->{_error} = "Failed to parse Excel file";
            return undef;
        }
    };
    if ($@) {
        $self->{_error} = "Failed to parse Excel file: $@";
        Common::Log::Print( $self->{_error} );
        return undef;
    }

    return 1;
}

sub _fetchRow {
    my $self = shift;
    my $sheet = $self->excel->Worksheet(0) || return;

    my $row = $sheet->{Cells}->[ $self->{_currentRow} ];

    my @cols;
    my $maxCol = $sheet->{MaxCol} + 1;

    for ( my $col = 0 ; $col < $maxCol ; $col++ ) {
        my $cell = $row->[$col];
        $cols[$col] = $self->_clean( $cell ? $cell->value() : undef );
    }

    return @cols;
}

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