package RPS::Import::WMG::WirelessProc;

use strict;

use Date::Calc qw(Days_in_Month);

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

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

use constant FIELD_BILLTO  => 0;
use constant FIELD_SERVICE => 1;
use constant FIELD_SELLTO  => 2;

use constant FIELD_SELLSVC   => 3;
use constant FIELD_DATE      => 4;
use constant FIELD_ARTIST    => 6;
use constant FIELD_LABEL     => 7;
use constant FIELD_TRACK     => 8;
use constant FIELD_UNITS     => 9;
use constant FIELD_RETAIL    => 10;
use constant FIELD_PRICE     => 14;
use constant FIELD_FORMAT    => 15;
use constant FIELD_ISRC      => 17;
use constant FIELD_GRID      => 18;
use constant FIELD_PRICETYPE => 19;

# public methods

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

    my $fileObj = $args{file};
    my $lines   = $args{lines};

    my $file = $self->_getFileSpecs( $lines->[0] );
    return undef unless ( ref $file eq 'HASH' );

    # warner wireless files are atomic
    $self->{fileServiceID} = $file->{serviceID};
    $fileObj->ServiceID( $file->{serviceID} );
    $fileObj->Atomic(1);
    $fileObj->Save();

    my $linenum = 1;
    my %errors  = ();

    foreach my $line (@$lines) {
        my $prodtype = RPS::File::Sale::TYPE_TRACK;

        my $serviceID;
        unless ( $serviceID = $self->getServiceID( $line->[FIELD_SELLSVC] ) ) {
            $self->errstr('unknown service');
            print STDERR "can't map '" . $line->[FIELD_SELLSVC] . "' to service_id\n" unless ( $errors{ $line->[FIELD_SELLSVC] } );
            $errors{ $line->[FIELD_SELLSVC] } = 1;
        } else {
            my @sellTo = RPS::Import::WMG::Util::getWirelessSellto( $serviceID, $file->{billTo} );
            unless ( $sellTo[0] && $sellTo[0] == $line->[FIELD_SELLTO] ) {
                $self->warning();
                print STDERR "sellto mapping: $sellTo[0] doesn't match file\n" unless ( $errors{$serviceID} );
                $errors{$serviceID} = 1;
            }
        }

        $line->[FIELD_UNITS] =~ s/\.\d\d$//;
        $line->[FIELD_UNITS] =~ s/\D+//g;

        my $artist  = $line->[FIELD_ARTIST];
        my $label   = $line->[FIELD_LABEL];
        my $isrc    = normalize_isrc( $line->[FIELD_ISRC] );
        my $grid    = $line->[FIELD_GRID];
        my $track   = $line->[FIELD_TRACK];
        my ($units) = $line->[FIELD_UNITS] =~ /^(\d+)$/;
        $units *= -1 if ( $line->[FIELD_PRICE] =~ s/\((.+)\)/$1/ );
        my ($price)   = $line->[FIELD_PRICE] =~ /\$(\d*\.?\d+)/;
        my ($retail)  = $line->[FIELD_RETAIL] =~ /\$(\d*\.?\d+)/;
        my $priceType = $line->[FIELD_PRICETYPE];

        if ( $units && $price && $track ) {
            my $ppdRate = $retail ? $price / $retail : '';
            my $sale = RPS::Import::SaleRec->new();

            my $format = '';
            my $fmt    = $line->[FIELD_FORMAT];
            $fmt =~ s/^e//i;
            unless ( $format = RPS::Import::WMG::Util::getWirelessFormatTypeID($fmt) ) {
                $self->warning();
                print STDERR "unknown format mapping: $fmt\n" unless $errors{$fmt};
                $errors{$fmt} = 1;
            }

            $sale->productType($prodtype);
            $sale->formatType($format);
            $sale->dateBegin( $file->{dateBegin} );
            $sale->dateEnd( $file->{dateEnd} );
            $sale->clientProductID($grid);
            $sale->isrc($isrc);
            $sale->artistName($artist);
            $sale->trackName($track);
            $sale->labelName($label);
            $sale->units($units);
            $sale->price($price);
            $sale->wholesaleRate($ppdRate);
            $sale->retail($retail);
            $sale->priceType($priceType);
            $sale->lineNum($linenum);

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

    $self->warning() if ( keys %errors );
    return $linenum;
}

#
# Private methods
#

sub _getFileSpecs {
    my $self = shift;
    my $line = shift;
    my $serviceID;

    $line->[FIELD_DATE] =~ m/^(\d{4})(\d\d)\d\d$/;
    my ( $year, $month ) = ( $1, $2 );

    unless ( $serviceID = $self->getServiceID( $line->[FIELD_SERVICE] ) ) {
        $self->errstr('unknown service');
        print STDERR "can't map '" . $line->[FIELD_SERVICE] . "' to service_id\n";
        return undef;
    }

    my @billTo = RPS::Import::WMG::Util::getWirelessBillto($serviceID);
    if ( $billTo[0] ) {
        unless ( $billTo[0] == $line->[FIELD_BILLTO] ) {
            $self->warning();
            print STDERR "billto mapping: $billTo[0] doesn't match file\n";
        }
    } else {
        $self->warning();
        print STDERR "billto mapping: $serviceID doesn't exist\n";
        $billTo[0] = 0;
    }

    return {
        serviceID => $serviceID,
        dateBegin => sprintf( "%d-%02d-01", $year, $month ),
        dateEnd   => sprintf( "%d-%02d-%d", $year, $month, Days_in_Month( $year, $month ) ),
        billTo    => $billTo[0],
    };
}

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