package RPS::Import::MusicMatchStream;

use strict;


use Date::Calc qw(Days_in_Month Decode_Month);

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

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

# map version_num to the field order
my %field_map = (
				  2 => {
						'usertype'	=> 1,
						'playtype'	=> 2,
						'stafplay'	=> 3,
						'isrc'		=> 6,
						'upc'		=> 7,
						'tracknum'	=> 9,
						'track'		=> 10,
						'artist'	=> 11,
						'album'		=> 12,
						'units'		=> 13,
						},
				  3 => {
						'usertype'	=> 1,
						'playtype'	=> 2,
						'stafplay'	=> 3,
						'isrc'		=> 6,
						'upc'		=> 7,
						'tracknum'	=> 9,
						'track'		=> 10,
						'artist'	=> 11,
						'album'		=> 12,
						'label'		=> 13,
						'units'		=> 14,
						},
				  4 => {
						'usertype'	=> 1,
						'playtype'	=> 2,
						'stafplay'	=> 3,
						'isrc'		=> 6,
						'upc'		=> 7,
						'tracknum'	=> 9,
						'track'		=> 10,
						'artist'	=> 11,
						'album'		=> 12,
						'label'		=> 13,
						'units'		=> 14,
						'price'		=> 15,
						},
				 );

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

#public methods

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

	my $retval = undef;
	my $lines = $args{lines};
	my $fileObj = $args{file};
	my $fileName = $fileObj->OrigFileName;
	my $version = $fileObj->VersionNum;

    unless ($version && exists $field_map{$version})
    {
        $self->errstr("wrong version");
        return undef;
    }

	if ($lines && $fileName)
	{
		my ($dateBegin, $dateEnd) = $self->_getDates($fileName);

		unless ($dateBegin && $dateEnd)
        {
            $self->errstr("couldn't get dates");
            return undef;
        }

        my $offsets = $field_map{$version};

        my $linenum = 1;
        foreach my $line(@$lines)
        {
            if ($linenum > 1 
             && $line->[$offsets->{'playtype'}] =~ m/^Full$/i)
            {
                my $prodtype	= RPS::File::Sale::TYPE_TRACK;
                my $format		= RPS::File::Sale::FORMAT_STREAM;
                my $isrc		= Common::Util::normalize_isrc($line->[$offsets->{'isrc'}]);
                my $upc			= Common::Util::normalize_upc($line->[$offsets->{'upc'}]);
                my $artist		= $line->[$offsets->{'artist'}];
                my $album		= $line->[$offsets->{'album'}];
                my $track		= $line->[$offsets->{'track'}];
                my ($trackNum)	= $line->[$offsets->{'tracknum'}] =~ m/^(\d+)$/;
                my ($units)		= $line->[$offsets->{'units'}] =~ m/^(-?\d+)$/;

                # Set the 'free track flag' if its a trial track, and
                # not a stafplay.
                #
                my $free = ( ($line->[$offsets->{'usertype'}] =~ m/^Trial$/i && $line->[$offsets->{'stafplay'}] =~ m/^No$/i) ? 1 : 0 );

                # for version 3 & 4
                my $label;
                $label = $line->[$offsets->{'label'}] if (exists $offsets->{'label'});

                # for version 4
                my $price;
                $price = $line->[$offsets->{'price'}] if (exists $offsets->{'price'});

                $price = $price / $units if ($price && $units != 0);

                if ($units && ($artist || $album) && $track)
                {
                    my $sale = RPS::Import::SaleRec->new();

                    $sale->productType($prodtype);
                    $sale->formatType($format);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->isrc($isrc);
                    $sale->upc($upc);
                    $sale->artistName($artist);
                    $sale->albumName($album);
                    $sale->trackName($track);
                    $sale->trackNum($trackNum);
                    $sale->units($units);
                    ## taking out price, because it doesn't always come out right due to 
                    ## MusicMatch's rounding issues that can't we can't address with what
                    ## is in the file...
                    $sale->price($price) if ($price); # version 4
                    $sale->labelName($label) if ($label); # version 3 & 4
                    $sale->lineNum($linenum);
                    $sale->free($free);
                    $sale->countryCode('US');

                    $self->_insertSale(sale => $sale);
                }
            }
            $linenum++;
        }
        $retval = $linenum;
	}

	return $retval;
}

#
# Private methods
#


sub _getDates
{
	my $self = shift;
	my $fileName = shift;
    my %months = (
        January   => '01',
        February  => '02',
        March     => '03',
        April     => '04',
        May       => '05',
        June      => '06',
        July      => '07',
        August    => '08',
        September => '09',
        October   => '10',
        November  => '11',
        December  => '12',
    );
    
	my $dateBegin;
	my $dateEnd;

    my ($year, $month, $monthName);
    if($fileName =~ /(20\d\d)(01|02|03|04|05|06|07|08|09|10|11|12)/) {
	    ($year, $month) = $fileName =~ m/(20\d\d)(01|02|03|04|05|06|07|08|09|10|11|12)/;
    }
    elsif($fileName =~ /BPYahoo/) {
        $fileName =~ m/BPYahoo(\w\w\w)(\d\d)/;
        $monthName = $1;
        $year = $2;
        $year += 2000;
        $month = Decode_Month($monthName);
    }
    elsif($fileName =~ /(\w{3}) (\d+) Strms/) {
        $monthName = $1;
        $year = 2000 + $2;
        $month = Decode_Month($monthName);
    }

	if ($year && $month)
	{
		$dateBegin = sprintf("%04d-%02d-%02d", $year, $month, 1);
		$dateEnd = sprintf("%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month));
	}

	return ($dateBegin, $dateEnd);
}

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