package RPS::Import::OtherMusic;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

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

use lib '/app/tools/rps/lib';

use RPS::File::Sale;
use base 'RPS::Import::Importer';

my %field_map = (
        1 => {
            isrc            => 0,
            upc             => 1,
            artist          => 2,
            title           => 3,
            svc_product_id  => 4,
            prod_type       => 5,
            units           => 6,
            price           => 7,
            format          => 9,
            country         => 10,
            label           => 13,
            currency        => 14,
            mechanicals     => 16,
        },
        2 => {
            label           => 0,
            isrc            => 1,
            upc             => 2,
            artist          => 3,
            title           => 4,
            svc_product_id  => 5,
            prod_type       => 6,
            units           => 7,
            price           => 10,
            format          => 12,
            country         => 13,
            currency        => 15,
            mechanicals     => 17,
        },
);          

#public methods

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

    my $fileObj = $args{file};
    my $version = $args{file}->VersionNum();
    my $fileName = $fileObj->OrigFileName;
    #my $version = $args{version}; # for cmd-line testing
    #my $fileName = $args{OrigFileName};
    my $offsets = $field_map{$version}; 
    my $lines = $args{lines};

    return 0 unless ($lines);
    my ($dateBegin, $dateEnd) = $self->_getDates($version,$fileName);
    unless ($dateBegin && $dateEnd)
    {
        $self->errstr("couldn't get dates");
        print STDERR "fname: $fileName\n";
        return undef;
    }
    
    my $linenum = 1;
    foreach my $line(@$lines)
    {
        my ($track, $album);
        my $prodType = lc $line->[$offsets->{prod_type}];

        my $isrc        = Common::Util::normalize_isrc($line->[$offsets->{isrc}]);
        my $upc         = Common::Util::normalize_upc($line->[$offsets->{upc}]);
        my $artist      = $line->[$offsets->{artist}];
        my $svcProd     = $line->[$offsets->{svc_product_id}];
        my ($units)     = $line->[$offsets->{units}] =~ m/^(\d+)$/;
        my ($price)     = $line->[$offsets->{price}];
        my $format      = $line->[$offsets->{format}] =~ m/down/i ? RPS::File::Sale::FORMAT_DOWNLOAD : undef;
        my $country     = uc $line->[$offsets->{country}] || 'US';
        my $label       = $line->[$offsets->{label}];
        my $currency    = uc $line->[$offsets->{currency}] || 'USD';
        my ($mechPrice) = $line->[$offsets->{mechanicals}] =~ m/^(-?\d+\.\d+)$/;

        if ($mechPrice && $mechPrice > 0)
        {
            $self->errstr('invalid row');
            print STDERR "non-zero mechanicals not allowed ($linenum)\n";
            return undef;
        }

        if ($format && $price && $units && $artist)
        {
            $price /= $units if($units>1);
            if ($prodType eq 'track')
            {
                $prodType = RPS::File::Sale::TYPE_TRACK;
                $track = $line->[$offsets->{title}];
            }
            elsif ($prodType eq 'album')
            {
                $prodType = RPS::File::Sale::TYPE_ALBUM;
                $album = $line->[$offsets->{title}];
            }
            else
            {
                $self->errstr('unknown product type');
                print STDERR "prod-type: $prodType\n";
                return undef;
            }

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


            $sale->productType($prodType);
            $sale->formatType($format);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->serviceProductID($svcProd);
            $sale->upc($upc);
            $sale->isrc($isrc);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->trackName($track);
            $sale->units($units);
            $sale->price($price);
            $sale->labelName($label);
            $sale->countryCode($country);
            $sale->currencyCode($currency);
            $sale->lineNum($linenum);
            #$args{dumper}($sale);  ## for cmd-line testing
            $self->_insertSale(sale => $sale);
        }
        #else { print STDERR "Skip line: " . $linenum . " f: " . $format . " p:" . $price . " u: ".$units ." a:".$artist . "\n"; }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

sub _getDates
{
    my $self = shift;
    my $vrsn = shift;
    my $fName = shift;
    my ($month,$year);
    if($vrsn==1) {
        return undef unless ($fName =~ m/\D(\d\d)\D+(\d\d)\D/);
        ($month, $year) = ($1, $2+2000);
    }
    else {
        if ($fName =~ m/(\d{4})\D(\d+)\D(\d+)/)
        {
          ($month, $year) = ($2,$1);
        } 
        elsif ($fName =~ m/other music (\D+) (\d{4})/)
        {
          ($month, $year) = (Decode_Month($1),$2);
        }
        else 
        {
          return undef
        }
    }

    return (
        Common::Util::normalize_date(join('-', $year, $month,1)),
        Common::Util::normalize_date(join('-', $year, $month, Days_in_Month($year, $month))),
   );
}

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