package RPS::Import::WMG::AmpdBundles;

use strict;

use Date::Calc qw(Days_in_Month);

use lib '/app/tools/common/lib';
use Common::Util qw(normalize_isrc normalize_upc);

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

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

my %field_map = (
    5 => {
        artist   => 0,
        track    => 1,
        format   => 2,
        isrc     => 3,
        retail   => 7,
        price    => 8,
        units    => 9,
        date_row => 1,
        date_col => 1,
    },
    6 => {
        artist   => 0,
        track    => 1,
        format   => 2,
        isrc     => 3,
        upc      => 4,
        retail   => 8,
        price    => 9,
        units    => 10,
        date_row => 1,
        date_col => 1,
    },
);

# public methods

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

    my $fileObj = $args{file};
    my $version = $self->_version();
    my $offsets = $field_map{$version};

    my $lines = $args{sheets}->[1];
    return 0 unless ($lines);

    my ( $dateBegin, $dateEnd ) = _getDates( $lines->[ $offsets->{date_row} ][ $offsets->{date_col} ] );
    unless ( $dateBegin && $dateEnd ) {
        $self->errstr("couldn't get dates");
        print STDERR "date: " . $lines->[ $offsets->{date_row} ][ $offsets->{date_col} ] . "\n";
        return undef;
    }

    my $linenum       = 1;
    my $prodtype      = RPS::File::Sale::TYPE_TRACK;
    my $formatDefault = RPS::File::Sale::FORMAT_DUALDOWNLOAD;
    my $priceType     = 'Standard/Bundle';

    my @billTo = RPS::Import::WMG::Util::getWirelessBillto( $self->{fileServiceID} );
    if ( $billTo[0] ) {
        unless ( RPS::Import::WMG::Util::getWirelessSellto( $self->{fileServiceID}, $billTo[0] ) ) {
            $self->warning();
            print STDERR "unknown sellto mapping: $billTo[0]\n";
        }
    } else {
        $self->warning();
        print STDERR "unknown billto mapping: $self->{fileServiceID}\n";
    }

    $fileObj->Atomic(1);
    $fileObj->Save();

    my %errors = ();

    foreach my $line (@$lines) {
        my $artist = $line->[ $offsets->{artist} ];
        my $track  = $line->[ $offsets->{track} ];
        my $isrc   = normalize_isrc( $line->[ $offsets->{isrc} ] );
        my $upc    = $version == 6 ? normalize_upc( $line->[ $offsets->{upc} ] ) : '';
        my $retail = $self->numeric( $line->[ $offsets->{retail} ] );
        my $price  = $self->numeric( $line->[ $offsets->{price} ] );
        my $units  = $self->numeric( $line->[ $offsets->{units} ] );

        # which is the real rate?
        my $rate = defined $retail && $retail != 0 ? $price / $retail : '';

        if ( $units && $retail && ( $artist || $track ) ) {
            my $format = lc $line->[ $offsets->{format} ];
            my $formatID =
                $format eq 'mod'
              ? $formatDefault
              : RPS::Import::WMG::Util::getWirelessFormatTypeID($format);

            unless ($formatID) {
                unless ( $errors{$format} ) {
                    $self->errstr('unknown format');
                    print STDERR "unknown format: $format\n";
                    $errors{$format} = 1;
                }
                $linenum++;
                next;
            }

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

            $sale->artistName($artist);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->formatType($formatID);
            $sale->isrc($isrc);
            $sale->lineNum($linenum);
            $sale->price($price);
            $sale->productType($prodtype);
            $sale->retail($retail);
            $sale->priceType($priceType);
            $sale->trackName($track);
            $sale->units($units);
            $sale->upc($upc);
            $sale->wholesaleRate($rate);

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

#
# Private methods
#

sub _getDates {
    my $date = shift;

    my ( $month, $year );
    if ( $date =~ m/^(\d+)\D\d\d\D(\d\d\d\d)$/ ) {
        ( $month, $year ) = ( $1, $2 );
    } elsif ( $date =~ m/^(\d\d\d\d)\D(\d+)\D\d\d$/ ) {
        ( $year, $month ) = ( $1, $2 );
    } else {
        return;
    }

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

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