package RPS::Import::INGrooves;

use strict;

# !!!!!!!!!!!!!!!!!!!!!!!!!
#
# This file is deprecated.  Version 1 and 2 are now handled in INGrooves2.pm
# 
# !!!!!!!!!!!!!!!!!!!!!!!!!





#use Date::Calc qw(Days_in_Month);

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

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 = (
    1 => {
        beginDate   =>  0,
        vendor      =>  1,
        endDate     =>  2,
        track       =>  3,
        album       =>  4,
        artist      =>  6,
        isrc        =>  7,
        upc         =>  8,
        country     => 11,
        units       => 12,
        royalty     => 16,
    },
    2 => {
        beginDate   =>  0,
        vendor      =>  1,
        endDate     =>  2,
        track       =>  3,
        album       =>  5,
        artist      =>  6,
        isrc        =>  7,
        upc         =>  8,
        country     => 11,
        units       => 12,
        mechanical  => 14,
        admin       => 15,
        royalty     => 16,
    },
);

### Public Methods ###

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

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

    my $version = $self->_version();
    return unless ($version);

    my $sheets = $args{sheets};
    return unless ($sheets);

    my $lines  = $sheets->[1];  # We need to look at the second sheet.
    return unless ($lines);
    shift @$lines;              # We don't care about the header line.
    my $linenum = 2;

    my $offsets = $field_map{$version};
    my %errors = ();
    my %service_format_map = (
    );

    foreach my $line (@$lines) {
        my $artist      = $line->[ $offsets->{artist}    ];
        my $album       = $line->[ $offsets->{album}     ];
        my $country     = $line->[ $offsets->{country}   ];
        my $date_b      = $line->[ $offsets->{beginDate} ];
        my $date_e      = $line->[ $offsets->{endDate}   ];
        my $isrc        = $line->[ $offsets->{isrc}      ];
        my $price       = $self->numeric($line->[ $offsets->{royalty} ]);
        my $mechanical  = $line->[$offsets->{mechanical}] if(defined $offsets->{mechanical} && $line->[$offsets->{mechanical}] ne "");
        my $adminFee    = $line->[$offsets->{admin}] if(defined $offsets->{admin} && $line->[$offsets->{admin}] ne ""); 
        my $svc_fmt     = $line->[ $offsets->{vendor}    ];
        my $track       = $line->[ $offsets->{track}     ];
        my $units       = $self->numeric($line->[ $offsets->{units} ]);
        my $upc         = $line->[ $offsets->{upc}       ];
        $price          += $mechanical if(defined $mechanical);
        $price          += $adminFee if(defined $adminFee);

        next unless ($price && $units && $artist && ($track || $album));

        $price = $price / $units; # We won't get here with 0 units.

        $country = 'us' unless $country;
        $country =~ s/\,\s.*$//;
        if (exists $Common::Consts::COUNTRY_CODE{ lc $country }) {
            $country = $Common::Consts::COUNTRY_CODE{ lc $country };
        }
        else {
            $self->errstr("unknown country '$country'");
            return;
        }

        my ($service, $format);
        if ($service_format_map{$svc_fmt})
        {
            ($service, $format) = @{ $service_format_map{$svc_fmt} };
        }
        elsif (!exists $errors{$svc_fmt})
        {
            unless ($service_format_map{$svc_fmt} = $self->_parse_svc_fmt($svc_fmt))
            {
                $self->errstr('unknown service');
                print STDERR "unknown service: $svc_fmt\n";
                $errors{$svc_fmt} = 1;
                next;
            }
            ($service, $format) = @{ $service_format_map{$svc_fmt} };
        }

        my ($dateBegin, $dateEnd) = $self->_getDates($date_b, $date_e);
        unless ($dateBegin && $dateEnd) {
            $self->errstr("couldn't get dates from '$date_b' or '$date_e'");
            return;
        }

        my $prodtype = ($album && !$track) ? RPS::File::Sale::TYPE_ALBUM : RPS::File::Sale::TYPE_TRACK;

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

        $sale->albumName($album);
        $sale->artistName($artist);
        $sale->countryCode($country);
        $sale->dateBegin($dateBegin);
        $sale->dateEnd($dateEnd);
        $sale->formatType($format);
        $sale->isrc($isrc) if ($isrc);
        $sale->lineNum($linenum);
        $sale->price($price);
        $sale->productType($prodtype);
        $sale->serviceID($service);
        $sale->trackName($track);
        $sale->units($units);
        $sale->upc($upc) if ($upc);

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

    return $linenum;
}

#
# Private methods
#


my $YYYY = qr/[0-9]{4}/;
my $MM   = qr/(?:0[1-9]|1[0-2]|[1-9])/;
my $DD   = qr/(?:0[1-9]|[12][0-9]|3[01]|[1-9])/;
my $Sep  = qr/[.\/-]/;
my $DATE = qr/($MM)$Sep($DD)$Sep($YYYY)/;

my $DATE_FORMAT = '%4d-%02d-%02d';

sub _getDates {
    my $self  = shift;
    my @dates = @_;

    for my $date (@dates) {
        if ($date =~ /$DATE/) {
            my ($year, $month, $day) = ($3, $1, $2);
            $date  = sprintf($DATE_FORMAT, $year, $month, $day);
        } else {
            $self->errstr("couldn't determine date from '$date'");
            return;
        }
    }

    return @dates;
}

sub _parse_svc_fmt
{
    my $self = shift;
    my $svcFmt = lc $_[0];

    my $format =
        $svcFmt =~ s/\s(ad supported)?\s*stream retail sales.*$// ? RPS::File::Sale::FORMAT_STREAM :
        $svcFmt =~ s/\s(download|burn|subscription)?\s*retail sales.*$// ? RPS::File::Sale::FORMAT_DOWNLOAD : RPS::File::Sale::FORMAT_DOWNLOAD;
        $svcFmt =~ s/\s+(net|now|port)\b/$1/; # why do they put spaces there??
        $svcFmt =~ s/\s//g if($svcFmt =~ /pacific/);
        $svcFmt =~ s/\s//g if($svcFmt =~ /play it tonight/i);
        $svcFmt =~ s/digital.*$// if($svcFmt =~ /juno/i);
    my $svcID = $self->getServiceID($svcFmt);
    return $svcID ? [ $self->getServiceID($svcFmt), $format ] : undef;
}

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