package RPS::Import::eMusicPre04;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

use lib '/app/tools/common/lib';
use Common::Util;

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

my %field_map = (
    9 => {
        'upc'    => 0,
        'track'  => 1,
        'artist' => 2,
        'album'  => 3,
        'units'  => 4,
        'price'  => 6,
    },

    10 => {
        'upc'    => 0,
        'type'   => 1,
        'name'   => 2,
        'artist' => 3,
        'units'  => 8,
        'price'  => 10,
    },

    11 => {
        'upc'    => 0,
        'type'   => 1,
        'name'   => 2,
        'artist' => 3,
        'units'  => 8,
        'price'  => 10,
    },
);

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

    my $lines = $args{lines};

    my $fileObj = $args{file};
    ##my $version = $args{version}; # for cmd-line testing
    my $version = $fileObj->VersionNum;

    return undef unless ( $lines && $version );
    my $offsets = $field_map{$version};

    my ( $dateBegin, $dateEnd, $sub, $rate, $total ) = $self->_parseSummary($lines);

    unless ( $dateBegin && $dateEnd && defined $sub && defined $rate && defined $total ) {
        $self->errstr("missing required summary data");
        print STDERR "dB:$dateBegin dE:$dateEnd sub:$sub rate:$rate t:$total\n";
        return undef;
    }
    print STDERR "using sub:$sub rate:$rate t:$total\n";

    my $label;

    my $header = 1;    # flag

    my $linenum = 1;
    foreach my $line (@$lines) {
        ## skip header
        if ( $header && $line->[0] ne 'UPC' ) {
            $linenum++;
            next;
        }
        $header = 0;

        ## skip empty lines, get labels
        if ( $line->[0] eq '' ) {
            $linenum++;
            next;
        } elsif ( $line->[0] =~ m/^([A-Z][A-Z0-9\s]+)/ ) {
            $label = $1;
            $linenum++;
            next;
        }

        my $format  = RPS::File::Sale::FORMAT_VPD;
        my $upc     = Common::Util::normalize_upc( $line->[ $offsets->{'upc'} ] );
        my $artist  = $line->[ $offsets->{'artist'} ];
        my ($units) = $line->[ $offsets->{'units'} ] =~ m/^(\d+)$/;
        my $price   = $line->[ $offsets->{'price'} ];

        my ( $prodtype, $track, $album );

        if ( $version == 9 ) {
            $prodtype = RPS::File::Sale::TYPE_TRACK;
            $track    = $line->[ $offsets->{'track'} ];
            $album    = $line->[ $offsets->{'album'} ];

        } elsif ( $version == 10 || $version == 11 ) {
            if ( $line->[ $offsets->{'type'} ] eq 'A' ) {
                $prodtype = RPS::File::Sale::TYPE_ALBUM;
                $album    = $line->[ $offsets->{'name'} ];
                $track    = "";
            } elsif ( $line->[ $offsets->{'type'} ] eq 'T' ) {
                $prodtype = RPS::File::Sale::TYPE_TRACK;
                $track    = $line->[ $offsets->{'name'} ];
                $album    = "";
            }
        }

        if ( $upc && $artist && $units && $price ) {
            my $netPrice = ( $price / $units - $sub ) * $rate;

            if ( $netPrice < 0 ) {
                $netPrice = abs($netPrice);
                $units    = (-1) * abs($units);
            }

            # negative price is ok so the following line does not apply to this file
            #$netPrice = 0 if $netPrice < 0; # allow negative price

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

            $sale->productType($prodtype);
            $sale->formatType($format);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->upc($upc);
            $sale->trackName($track);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->labelName($label);
            $sale->units($units);
            $sale->price($netPrice);
            $sale->lineNum($linenum);
            $sale->countryCode('US');

            ##$args{dumper}($sale);  ## for cmd-line testing
            $self->_insertSale( sale => $sale );
        }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

sub _parseSummary {
    my $self  = shift;
    my $lines = shift;

    my ( $dateBegin, $dateEnd, $tUnits, $share, $tRoyalty );
    my $deductions = 0;

    foreach my $line (@$lines) {
        if ( $line->[0] =~ m/^Through Date/ && $line->[2] =~ m#\d+[-/]\d+[-/]\d+# ) {    # date
            $dateEnd = Common::Util::normalize_date( $line->[2] );
            $dateEnd =~ m/^(\d{4})-(\d\d)/;
            $dateBegin = sprintf( "%d-%02d-01", $1, $2 - 2 );
        } elsif ( $line->[9] < 0 && $line->[0] !~ m/^Returns$/ ) {                       # deductions
            $deductions += $line->[9];
        } elsif ( $line->[0] =~ m/^Net Units Sales/ && $line->[8] =~ m/^\d+$/ ) {        # total units
            $tUnits = $line->[8];
        } elsif ( $line->[0] =~ m/^Royalty Earned This Period/ && $line->[8] =~ m/^\%?(\d+[.]?\d+)/ ) {    # share percentage
            $share = $1 < 1 ? $1 : $1 / 100;
            $tRoyalty = $line->[9];
            last;
        }
    }
    return 0 unless $tUnits;

    $deductions *= -1;                                                                                     # make it positive
    return ( $dateBegin, $dateEnd, $deductions / $tUnits, $share, $tRoyalty );
}

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