package Finance::Bank::BR::Santander::Spreadsheet;

use strict;
use warnings;

=head1 COPYRIGHT AND LICENSE

  Copyright (C) 2015 Thadeu Lima de Souza Cascardo <cascardo@cascardo.eti.br>

  This program is free software; you can redistribute it and/or modify it under
  the terms of the GNU General Public License; either version 2 of the License,
  or (at your option) any later version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.

=cut

use Spreadsheet::ParseExcel::Simple;

our $VERSION = '0.01';

sub new {
    my $class = shift;
    my $self = {};
    bless $self, $class;
    $self->_init;
    $self->load(@_);
    return $self;
}

sub _init {
    my $self = shift;
    $self->{balance} = 0;
    $self->{statement} = [];
}

sub _parse {
    my $self = shift;
    my $xls = shift;
    my @sheets = $xls->sheets;
    my $sheet = $sheets[0];
    if ($sheet->has_data) {
        my @header = $sheet->next_row;
    }
    while ($sheet->has_data) {
        my @line = $sheet->next_row;
        my $obj = {
            'date' => $line[0],
            'name' => $line[2],
            'extra' => $line[3],
            'value' => $line[4],
            'balance' => $line[5],
        };
        push @{$self->{statement}}, $obj;
        $self->{balance} = $line[5];
    }
}

sub load {
    my $self = shift;
    my $filename = shift;
    if (defined($filename)) {
        my $xls = Spreadsheet::ParseExcel::Simple->read($filename);
        if (!defined($xls)) {
            return;
        }
        $self->_parse($xls);
    }
}

sub balance {
    my $self = shift;
    return $self->{balance};
}

sub statement {
    my $self = shift;
    return $self->{statement};
}

1;
