package RPS::Import::IMN_Stream;

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';

# version mapping
my %field_map = (
    1 => {
        label  => 1,
        artist => 2,
        album  => 3,
        units  => 4,
    },
);

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

    my $lines    = $args{lines};
    my $fileObj  = $args{file};
    my $fileName = $fileObj->OrigFileName;

    #my $fileName = $args{OrigFileName}; # for cmd-line testing

    my $map = $field_map{ $fileObj->VersionNum };

    #my $map = $field_map{$args{version}}; # for cmd-line testing

    return undef unless $lines;
    my ( $dateBegin, $dateEnd ) = $self->_getDates($fileName);

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

    my $linenum = 1;
    foreach my $line (@$lines) {
        my $artist = $line->[ $map->{artist} ];
        my $album  = $line->[ $map->{album} ];
        my $label  = $line->[ $map->{label} ];
        my $units  = $self->_get_units( $line->[ $map->{units} ] );

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

            $sale->productType(RPS::File::Sale::TYPE_ALBUM);
            $sale->formatType(RPS::File::Sale::FORMAT_STREAM);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->labelName($label);
            $sale->units($units);
            $sale->lineNum($linenum);

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

    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my $self  = shift;
    my $fName = shift;
    my ( $qtr, $month, $year );

    return undef unless ( $fName =~ m/(\d)\D+Quarter\D+(\d{4})/i );

    ( $qtr, $year ) = ( $1, $2 );
    $month = ( $qtr * 3 ) - 2;

    return undef unless ( $month && $year );

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

sub _get_units {
    my $self    = shift;
    my $timeStr = shift;

    $timeStr =~ s/\s+/:/;
    my ( $day, $hr, $min, $sec ) = split /:/, $timeStr;

    return -1 unless ( $day =~ /^\d+$/ && $hr =~ /^\d+$/ && $min =~ /^\d+$/ && $sec =~ /^\d+$/ );
    my $units = ( $day * 1440 ) + ( $hr * 60 ) + $min;
    $units++ if ( $sec > 29 );

    return $units;
}

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