package RPS::Import::SprintStreams;

use strict;


use Date::Calc qw(Days_in_Month);

use lib '/app/tools/data_classes/lib';

use lib '/app/tools/rps/lib';
use RPS::File::Sale;
use RPS::Import::Importer;
use base 'RPS::Import::Importer';

use constant FIELD_UNITS    => 1;
use constant FIELD_ARTIST   => 3;
use constant FIELD_ALBUM    => 4;
use constant FIELD_TRACK    => 5;
use constant FIELD_LABEL    => 6;

sub _importLines
{
    my $self = shift;
    my %args = @_;

    my $lines = $args{lines};
    my $sheets = $args{sheets};
    my $fileName = $args{file}->OrigFileName;
    #my $fileName = $args{OrigFileName}; # for cmd-line testing
    return 0 unless $lines;

    my ($dateBegin, $dateEnd) = $self->_getDates($fileName);

    unless ($dateBegin && $dateEnd)
    {
        $self->errstr("couldn't get dates");
        print STDERR "date: $fileName\n";
        return 0;
    }

    my $prodType = RPS::File::Sale::TYPE_TRACK;
    my $formatType = RPS::File::Sale::FORMAT_STREAM;

    my $linenum = 1;
    foreach my $line(@$lines)
    {
        my $artist  = $line->[FIELD_ARTIST];
        my $album   = $line->[FIELD_ALBUM];
        my $track   = $line->[FIELD_TRACK];
        my $label   = $line->[FIELD_LABEL];
        my ($units) = $line->[FIELD_UNITS] =~ /^(\d+)$/;

        if ($units && $artist && $album && $track)
        {
            my $sale = RPS::Import::SaleRec->new();

            $sale->productType($prodType);
            $sale->formatType($formatType);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->trackName($track);
            $sale->labelName($label);
            $sale->units($units);
            $sale->lineNum($linenum);

            #$args{dumper}($sale); # for cmd-line testing
            $self->_insertSale(sale => $sale);
        } #else { print STDERR "skip: u: $units r: $artist a: $album t: $track ($linenum)\n" }
        $linenum++;
    }

    return $linenum;
}

#
# Private methods
#

sub _getDates
{
    my $self = shift;
    my $fileName = shift; # TotalReport_2006-Q1.xls

    $fileName =~ m/\D(\d{4})\Dq(\d)/i;
    my ($year, $month) = ($1, $2 * 3);
    return unless ($year && $month);

    return (
        sprintf("%d-%02d-01", $year, $month-2),
        sprintf("%d-%02d-%02d", $year, $month, Days_in_Month($year, $month))
    );
}

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