package RPS::Import::Muze;

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 => {
        prodID   => 0,
        trackNum => 2,
        artist   => 3,
        album    => 4,
        track    => 5,
        units    => 8,
    },
);

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 $prodID   = $line->[ $map->{prodID} ];
        my $artist   = $line->[ $map->{artist} ];
        my $album    = $line->[ $map->{album} ];
        my $track    = $line->[ $map->{track} ];
        my $trackNum = $line->[ $map->{trackNum} ];
        my ($units)  = $line->[ $map->{units} ] =~ m/^(\d+\.\d+)$/;

        if ( $units && $album && $track ) {
            $album =~ s/\s\*$//;

            # re-calc units
            $units = sprintf( "%0.0f", $units );

            my $sale = RPS::Import::SaleRec->new();

            $sale->productType(RPS::File::Sale::TYPE_TRACK);
            $sale->formatType(RPS::File::Sale::FORMAT_STREAM);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->serviceProductID($prodID);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->trackName($track);
            $sale->trackNum($trackNum);
            $sale->units($units);
            $sale->lineNum($linenum);

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

    return $linenum;
}

#
# Private methods
#

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

    if ( $fName =~ m/WEA(\d)(\d\d)\./ ) {
        ( $month, $year ) = ( $2, $1 );
        $year += 2000;
    } elsif ( my ($d1) = $fName =~ m/(\d+)_\d+_/ ) {
        ($month) = $d1 =~ m/^(\d\d)/;
        ($year)  = $d1 =~ m/(\d{4})$/;
    }

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

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

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