package RPS::Import::MusicBrigade;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);
use Spreadsheet::ParseExcel;

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

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

my %field_map = (
    1 => {
        start_date          => 0,
        end_date            => 1,
        upc                 => 2,
        isrc                => 3,
        service_product_id  => 4,
        units               => 5,
        price               => 6,
        format              => 8,
        artist              => 10,
        track               => 11,
        label               => 12,
        plus_or_minus       => 14,
        country             => 15,
        currency            => 17,
    },
    2 => {
        start_date          => 0,
        end_date            => 1,
        isrc                => 2,
        units               => 3,
        format              => 4,
        artist              => 6,
        track               => 8,
        label               => 9,
        plus_or_minus       => 10,
        country             => 11,
        price               => 12,
        currency            => 14,
    },
    3 => {
        start_date          => 0,
        end_date            => 1,
        isrc                => 2,
        units               => 3,
        format              => 4,
        artist              => 6,
        track               => 8,
        label               => 9,
        plus_or_minus       => 10,
        country             => 11,
        price               => 12,
        currency            => 13,
    },
);

my %format_type = (
    D           => RPS::File::Sale::FORMAT_DOWNLOAD,
    R           => RPS::File::Sale::FORMAT_RINGTONE,
    S           => RPS::File::Sale::FORMAT_STREAM,
    Stream      => RPS::File::Sale::FORMAT_STREAM,
    V           => RPS::File::Sale::FORMAT_DOWNLOAD, # was FORMAT_VIDEO (FB1324)
    A           => RPS::File::Sale::FORMAT_DOWNLOAD,
);


#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 $sheet_count = 0;
    return undef unless (defined $args{sheets} && defined $version);

    my $sheet_names = $args{sheet_names};
	my $linenum;

    foreach my $sheet(@{ $args{sheets} }) {
        $linenum = 1;

	    foreach my $line (@$sheet) {
            my $dateBegin           = $line->[$offsets->{start_date}];
            my $dateEnd             = $line->[$offsets->{end_date}];
            my $isrc                = $line->[$offsets->{'isrc'}];
            my $upc                 = $line->[$offsets->{upc}] if(defined $offsets->{upc});
			my $artist		        = $line->[$offsets->{'artist'}];
			my $title		        = $line->[$offsets->{'track'}];
			my $units		        = $line->[$offsets->{'units'}];
			my $price	            = $line->[$offsets->{'price'}];
            my $label               = $line->[$offsets->{label}];
            my $currency            = $line->[$offsets->{currency}];
            my $country             = $line->[$offsets->{country}];
            my $service_product_id  = $line->[$offsets->{service_product_id}] if(defined $offsets->{service_product_id});
            my $product_type        = RPS::File::Sale::TYPE_TRACK;
            my $format              = RPS::File::Sale::FORMAT_DOWNLOAD;
            my $free                = 0;
            $format                 = $format_type{$line->[$offsets->{format}]} if($line->[$offsets->{format}] ne "");

            # The following line covers any format with the word 'stream' in it,
            # including 'video stream' which was retired and mapped to
            # FORMAT_STREAM in FB1324.
            #
            $format                 = RPS::File::Sale::FORMAT_STREAM if($format eq "" && $line->[$offsets->{format}] =~ /stream/i);


            my $mediaType = RPS::DB::Item::MediaType::kMediaTypeAudio;

            if( $line->[$offsets->{format}] =~ /^(V|Video Stream)$/i )
            {
                $mediaType  = RPS::DB::Item::MediaType::kMediaTypeVideo;
            }


            $product_type           = RPS::File::Sale::TYPE_ALBUM if($line->[$offsets->{format}] eq "A");
            $free                   = 1 if($price==0);

            if($line->[$offsets->{plus_or_minus}] ne "Sale") {
                $units *= -1 if($units>0);
                $price *= -1 if($price<0);
            }

			if ($units && $artist && $title && $artist ne "Artist") {
			    my $sale = RPS::Import::SaleRec->new();

				$sale->productType($product_type);
				$sale->formatType($format);
                $sale->mediaType($mediaType);
                $sale->isrc($isrc)if ($isrc ne "");
                $sale->upc($upc) if($upc ne "");
				$sale->dateBegin($dateBegin);
				$sale->dateEnd($dateEnd);
                $sale->currencyCode($currency);
                $sale->countryCode($country);
                $sale->serviceProductID($service_product_id) if($service_product_id ne "");
				$sale->artistName($artist);
				$sale->trackName($title) if($product_type eq RPS::File::Sale::TYPE_TRACK);
                $sale->albumName($title) if($product_type eq RPS::File::Sale::TYPE_ALBUM);
                $sale->labelName($label) if($label ne "");
				$sale->units($units);
				$sale->price($price);
                $sale->free($free);
				$sale->lineNum($linenum);
				$self->_insertSale(sale => $sale);
			}
            else { print STDERR "skip s:".$sheet_names->[$sheet_count]." l:".$linenum." u: $units p: $price a: $artist t: $title\n"; }
            $linenum++;
		}
        $sheet_count++;
	}

	return $linenum;
}

#
# Private methods
#

sub _getDates {
    my $passed_date = shift;
    my ($month,$monthName,$year,$qtr,$dateBegin,$dateEnd);
    $monthName = $passed_date;
    if($passed_date =~ m/(\w+)_(\d{4})/) {
        $year = $2;
        $monthName = $1;
    }
    $monthName =~ s/^.*_//g;
    $monthName = "jan" if($monthName =~ /jan/i);
    $monthName = "feb" if($monthName =~ /feb/i);
    $monthName = "mar" if($monthName =~ /mar/i);
    $monthName = "apr" if($monthName =~ /apr/i);
    $monthName = "may" if($monthName =~ /may/i);
    $monthName = "jun" if($monthName =~ /jun/i);
    $monthName = "jul" if($monthName =~ /jul/i);
    $monthName = "aug" if($monthName =~ /aug/i);
    $monthName = "sep" if($monthName =~ /sep/i);
    $monthName = "oct" if($monthName =~ /oct/i);
    $monthName = "nov" if($monthName =~ /nov/i);
    $monthName = "dec" if($monthName =~ /dec/i);
    $month = Decode_Month($monthName) if($month eq "" && $monthName ne "");
    if($month ne "" & $year ne "") {
        $dateBegin = $year."-".$month."-01";
        $dateEnd = $year."-".$month."-".sprintf("%02d",Days_in_Month($year,$month));
        return ($dateBegin,$dateEnd);
    }
    else {
        return undef;
    }
}

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