package RPS::Import::AMI;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

use lib '/app/tools/common/lib';
use Common::Util;
use Common::Consts qw(%COUNTRY_CODE);

use Common::Util qw(normalize_upc normalize_isrc normalize_date);

use lib '/app/tools/data_classes/lib';
use Client::Service;

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

my %field_map = (
                 1 => {
                        'label'     => 2,
                        'track'     => 3,
                        'tracknum'  => 4,
                        'artist'    => 5,
                        'album'     => 6,
                        'upc'       => 7,
                        'isrc'      => 8,
                        'units'     => 9,
                        'price'     => 11,
                      },
                 2 => {
                        'isrc'      => 4,
                        'upc'       => 5,
                        'label'     => 6,
                        'artist'    => 7,
                        'track'     => 8,
                        'units'     => 9,
                        'freeUnits' => 10,
                        'price'     => 11,
                 },
                 3 => {
                        'isrc'      => 3,
                        'upc'       => 4,
                        'label'     => 5,
                        'artist'    => 6,
                        'track'     => 7,
                        'units'     => 8,
                        'price'     => 9,
                 },
                 4 => {
                        'sheet'     => 1,
                        'isrc'      => 3,
                        'upc'       => 4,
                        'label'     => 5,
                        'artist'    => 6,
                        'track'     => 7,
                        'units'     => 8,
                        'price'     => 10,
                 },
                 5 => {
                        'isrc'      => 7,
                        'upc'       => 6,
                        'label'     => 0,
                        'artist'    => 3,
                        'album'     => 4,
                        'track'     => 1,
                        'units'     => 8,
                        'price'     => 10,
                        'freeUnits' => 9,
                 },
                 6 => {
                        'isrc'      => 10,
                        'upc'       => 9,
                        'label'     => 4,
                        'artist'    => 7,
                        'album'     => 8,
                        'track'     => 5,
                        'units'     => 11,
                        'price'     => 13,
                        'freeUnits' => 12,
                        'year'      => 2,
                        'quarter'   => 3,
                 },
                 7 => {
                    label           => 0,
                    track           => 1,
                    artist          => 2,
                    album           => 4,
                    upc             => 5,
                    units           => 6,
                    price           => 8,
                 },
                 8 => {
                    isrc      => 7,
                    upc       => 6,
                    artist    => 5,
                    track     => 4,
                    units     => 9,
                    price     => 19,
                    freeUnits => 10,
                 },
);

#public methods

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

	my $fileObj = $args{file};
    my $version = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();
    my $offsets = $field_map{$version};
    my $sheets = $args{sheets};

    return undef unless ($sheets && $version);

	my ($dateBegin, $dateEnd) = $self->_getDates($fileName);

    unless ($dateBegin && $dateEnd) {
        $self->errstr("couldn't get dates from:".$fileName);
        print STDERR "couldn't get dates from:".$fileName."\n";
        return undef;
    }

	my $linenum;
    foreach my $lines(@$sheets) {
        $linenum = 2 if ($version>4);
        $linenum = 1 if ($version<5 || $version==7);
	foreach my $line(@$lines) {
		if ($linenum > 1) {

            if ( $version == 6 )
            {
                ($dateBegin, $dateEnd) = $self->_getDates(
                   "Q". $line->[$offsets->{quarter}] . "-"
                      . $line->[$offsets->{year}] . "."
                );
            }

			my $prodtype	= RPS::File::Sale::TYPE_TRACK;
			my $format		= RPS::File::Sale::FORMAT_STREAM;
            my ($upc,$isrc) = split(" ",$line->[$offsets->{upc}]) if($version == 7);
			my $upc			= normalize_upc($line->[$offsets->{upc}]) if($version != 7);
			my $isrc		= normalize_isrc($line->[$offsets->{isrc}]) if($version != 7);
			my $artist		= $line->[$offsets->{'artist'}];
			my $track		= $line->[$offsets->{'track'}];
			my $label		= $line->[$offsets->{'label'}] if(defined $offsets->{label});
            my ($album, $trackNum, $freeUnits);

			$album		    = $line->[$offsets->{'album'}] if(defined $offsets->{album} && $line->[$offsets->{album}] ne "");
			$trackNum	    = $line->[$offsets->{'tracknum'}] =~ m/^(\d+)$/ if(defined $offsets->{tracknum});

            $freeUnits      = $line->[$offsets->{'freeUnits'}] if ($version == 2||$version==5||$version==8);
			my ($units)		= $line->[$offsets->{'units'}];
			my ($price)		= $line->[$offsets->{'price'}];

            $price = ($units != 0) ? ($price / $units) : 0;

			if (($units>0 || $freeUnits>0) && $artist && $artist !~ /Music Royalty Report/ && ($track || $isrc) && $track ne "Title") {
                my $sale;

                if ($units>0)
                {
				    $sale = RPS::Import::SaleRec->new();
				    $sale->productType($prodtype);
				    $sale->formatType($format);
				    $sale->dateBegin($dateBegin);
				    $sale->dateEnd($dateEnd);
				    $sale->upc($upc);
				    $sale->isrc($isrc) if(defined $offsets->{isrc});
				    $sale->artistName($artist);
				    $sale->albumName($album);
				    $sale->trackName($track);
				    $sale->labelName($label) if(defined $offsets->{label});
				    $sale->trackNum($trackNum);
				    $sale->price($price);
				    $sale->lineNum($linenum);
				    $sale->units($units);
				    $sale->countryCode('US');
				    $self->_insertSale(sale => $sale);
                }

                if ($freeUnits>0)
                {
                    $sale = RPS::Import::SaleRec->new();
                    $sale->productType($prodtype);
                    $sale->formatType($format);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->upc($upc);
                    $sale->isrc($isrc) if(defined $offsets->{isrc});
                    $sale->artistName($artist);
                    $sale->albumName($album);
                    $sale->trackName($track);
                    $sale->labelName($label) if(defined $offsets->{label});
                    $sale->trackNum($trackNum);
                    $sale->lineNum($linenum);
				    $sale->units($freeUnits);
				    $sale->free(1);
				    $sale->price(0);
				    $sale->countryCode('US');
				    $self->_insertSale(sale => $sale);
                }

			} #else { print STDERR "skipped l: $linenum u: $units p: $price fu: $freeUnits a: $artist t: $track u: $upc i: $isrc \n"; }
		}
		$linenum++;
    }
	}
	return $linenum;
}

#
# Private methods
#


sub _getDates {
	my $self = shift;
	my $date = shift;
    my ($qtr,$year);
    $date =~ s/\/.*\///g;
    if($date =~ m/Q(\d)\D(\d{4}).*\./) {
        ($qtr, $year) = ($1, $2);
    }
    elsif($date =~ m/(\d)Q(\d{2}).*\./) {
        ($qtr, $year) = ($1, $2);

        if ( $year =~ /^9\d$/ ) {
           $year = sprintf("%4d", 1900 + $year);
        } elsif ( $year =~ /^1\d$/ ) {
           $year = sprintf("%4d", 2000 + $year);
        }
    }
    elsif($date =~ m/Records\s(\d{4})\sQ(\d)/) {
        ($year, $qtr) = ($1, $2);
    }
    elsif($date =~ m/\s(\d{4})\sQ(\d)/) {
        ($year, $qtr) = ($1, $2);
    }
    elsif ($date =~ m/AMI_Warner_Royalty_Report (\w+) (\d{4})/) # AMI_Warner_Royalty_Report April 2008
    {
        $year = $2;
        my $month = Decode_Month($1);
        return (
                sprintf("%4d-%02d-01",$year,$month),
                sprintf("%4d-%02d-%02d",$year,$month,Days_in_Month($year,$month))
        );
    }
    else {
        return undef unless ($date =~ m/Q(\d)\D(\d{4}).*\./);
    }

    my ($dateBegin, $dateEnd);

    if ($qtr == 1) {
        $dateBegin = $year."-01-01";
        $dateEnd   = $year."-03-".Days_in_Month($year, 3);
    } elsif ($qtr == 2) {
        $dateBegin = $year."-04-01";
        $dateEnd   = $year."-06-".Days_in_Month($year, 6);
    } elsif ($qtr == 3) {
        $dateBegin = $year."-07-01";
        $dateEnd   = $year."-09-".Days_in_Month($year, 9);
    } elsif ($qtr == 4) {
        $dateBegin = $year."-10-01";
        $dateEnd   = $year."-12-".Days_in_Month($year, 12);
    } else {
        return undef;
    }

	return ($dateBegin, $dateEnd);
}

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