package RPS::Import::NewVisions;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days Decode_Month);

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

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';

# map version num to the field order
my %fieldMap =
(
	1 => {
        artist              => 0,
        title               => 1,
        client_product_id   => 2,
        format              => 5,
        units               => 6,
        price_link          => 7,
        isrc                => 10,
        price               => 3,
        data_start          => 16,
        rate_link           => 1,
	},
    2 => {
        date                => 0,
        artist              => 2,
        title               => 3,
        client_product_id   => 6,
        format              => 5,
        isrc                => 8,
        price               => 10,
    },
    3 => {
        artist              => 10,
        title               => 9,
        client_product_id   => 6,
        format              => 2,
        isrc                => 11,
        price_link          => 7,
        price               => 4,
        units               => 5,
        data_start          => 16,
        rate_link           => 2,
    },
    4 => {
        date                => 0,
        artist              => 1,
        title               => 2,
        client_product_id   => 5,
        format              => 4,
        isrc                => 7,
        price               => 9,
    },
    5 => {
        date                => 0,
        client_product_id   => 1,
        artist              => 2,
        title               => 3,
        units               => 4,
        isrc                => 5,
        format              => 6,
        price               => 4,
        price_link          => 6,
        data_start          => 14,
        rate_link           => 2,
    },
    6 => {
        artist              => 1,
        title               => 2,
        client_product_id   => 5,
        format              => 4,
        isrc                => 9,
        price               => 8,
    },
    7 => {
        artist              => 1,
        title               => 2,
        client_product_id   => 5,
        format              => 4,
        price               => 8,
    },
    8 => {
        date                => 0,
        artist              => 2,
        title               => 3,
        client_product_id   => 6,
        format              => 5,
        price               => 9,
    },
    9 => {
        artist              => 0,
        title               => 1,
        client_product_id   => 3,
        format              => 6,
        price_link          => 7,
        price               => 3,
        data_start          => 16,
        rate_link           => 1,
    },
    10=> {
        artist              => 0,
        title               => 1,
        client_product_id   => 2,
        format              => 5,
        price_link          => 6,
        price               => 3,
        data_start          => 16,
        rate_link           => 1,
    },
    11=> {
        artist              => 8,
        title               => 9,
        client_product_id   => 0,
        format              => 10,
        isrc                => 11,
        price_link          => 4,
        price               => 3,
        data_start          => 18,
        rate_link           => 2,
    },
    12 => {
        artist              => 0,
        title               => 1,
        client_product_id   => 2,
        format              => 5,
        price_link          => 7,
        price               => 3,
        data_start          => 15,
        rate_link           => 1,
    },
    14 => {
        artist              => 0,
        title               => 1,
        client_product_id   => 2,
        format              => 5,
        price_link          => 6,
        price               => 3,
        data_start          => 15,
        rate_link           => 1,
    },
);

#public methods

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

	my $fileObj = $args{file};
    my $version = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();
    #my $version = $args{version}; # cmd-line testing
    #my $fileName = $args{OrigFileName}; # cmd-line testing
    my $sheet_count = 0;
    return undef unless (defined $args{sheets} && defined $version);

	my $offsets = $fieldMap{$version};
    my $sheet_names = $args{sheet_names};
    my $header_found = 0;
    my $linenum = 1;
    my %prices;
    my ($dateBegin,$dateEnd);

    foreach my $sheet(@{ $args{sheets} }) {
        my $linenum = 1;
        if($sheet_names->[$sheet_count] =~ /statement/i && defined $offsets->{rate_link}) {
            foreach my $line(@$sheet) {
                if(($linenum>$offsets->{data_start})&&($line->[$offsets->{rate_link}] ne "")&&($line->[$offsets->{price}] ne "")) {
                    $line->[$offsets->{rate_link}] =~ s/\s//g;
                    my @price_parts = split("\@",lc $line->[$offsets->{rate_link}]);
                    $price_parts[0] =~ s/polys/ringtone/;
                    $price_parts[0] =~ s/reals/realtone/;
                    $price_parts[0] =~ s/ringtunes/realtone/;
                    $price_parts[1] =~ s/\.00//;
                    $price_parts[1] =~ s/\D//g;
                    $price_parts[1] = "a" if ($price_parts[1] eq "");
                    $prices{$price_parts[0]}{$price_parts[1]} = $line->[$offsets->{price}];
                    #print STDERR "Creating price(".$price_parts[0].")(" . $price_parts[1] . "): " . $line->[$offsets->{price}] . "\n";
                }
                $linenum++;
            }
        }
        elsif($sheet_names->[$sheet_count] !~ /statement/i) {
            ($dateBegin, $dateEnd) = $self->_getDates($sheet_names->[$sheet_count]) if ($sheet_names->[$sheet_count] =~ /(\w+)\D(\d{4})/);
            ($dateBegin, $dateEnd) = $self->_getDates($sheet_names->[$sheet_count]) if ($sheet_names->[$sheet_count] =~ /(\w+)\s(\d{4})/);
            ($dateBegin, $dateEnd) = $self->_getDates($sheet_names->[$sheet_count]) if ($version==3);

            foreach my $line (@$sheet) {
                if(defined $offsets->{date} && $line->[$offsets->{date}] ne "" && $line->[$offsets->{date}] ne "MONTH" && $line->[$offsets->{date}] ne "DIGITAL IDENTIFIER") {
                    #print STDERR "finding date from: ". $line->[$offsets->{date}]."-".$sheet_names->[$sheet_count]."\n";
                    ($dateBegin,$dateEnd) = $self->_getDates($line->[$offsets->{date}]."-".$sheet_names->[$sheet_count]);
                }
                my ($units,$price);
                my $artist      = $line->[$offsets->{artist}];
                my $isrc        = $line->[$offsets->{isrc}];
                my $title       = $line->[$offsets->{title}];
                my $currency    = "GBP";
                my $country     = "GB";
                my $client_product_id = $line->[$fieldMap{$version}{'client_product_id'}];
                my $format      = lc $line->[$offsets->{format}]; 
                $format         =~ s/\s//g;
                $format         =~ s/midi4c/ringtone/;
                $format         =~ s/spmidi/ringtone/;
                $format         =~ s/mp3/realtone/;
                $format         =~ s/rmfwav/realtone/;
                $format         =~ s/smafma2wav/realtone/;
                $format         =~ s/smafma3wav/realtone/;
                $format         =~ s/smafma2/ringtone/;
                $format         =~ s/smafma3/ringtone/;
                $format         =~ s/smaf/ringtone/;
                $format         =~ s/smf4/ringtone/;
                $format         =~ s/amrwb/realtone/;
                my $prodtype    = RPS::File::Sale::TYPE_TRACK;
                $units          = $line->[$offsets->{units}] if (defined $offsets->{units});
                $units = 1 if(($line->[$offsets->{units}] eq "")||(!defined $offsets->{units}));
                $line->[$offsets->{price_link}] = "a" if($version==3 || $version==5);
                #print STDERR "Price: (".$format.")(".$line->[$offsets->{price_link}].")\n";
                $price          = $prices{$format}{$line->[$offsets->{price_link}]} if(defined $offsets->{price_link});
                $price          = $line->[$offsets->{price}] if (! defined $offsets->{price_link});
                if($version==11 && defined $offsets->{price_link}) {
                    my $link    = lc $line->[$offsets->{price_link}];
                    $link       =~ s/TTSMS/sms/i;
                    $link       =~ s/VFLIVE/vodafonelive/i;
                    $link       =~ s/TTWAP/sms/i;
                    $price      = $prices{$link}{a};
                    if($fileName eq "New Visions 2005 05-06 SMS.xls") {
                        $price -= .3 if($line->[$offsets->{price_link}+1] =~ /\.jpg/);
                        $price -= .38 if($line->[$offsets->{price_link}+1] =~ /\.dd/i);
                        $price -= .38 if($line->[$offsets->{price_link}+1] =~ /\.rtttl/i);
                    }
                }
                $price += $price*.175;
                #print STDERR "Price (".$format.")(".$line->[$offsets->{price_link}]."):".$price."\n";

                if ($format =~ /ringtone/i) {
                    $format = RPS::File::Sale::FORMAT_RINGTONE;
                } elsif($format =~ /realtone/i) {
                    $format = RPS::File::Sale::FORMAT_RINGTONE; # was FORMAT_MASTERTONE (FB1324)
                }

                if ($units && $price && $title && $format && $title !~ /title/i)
                {
                    unless (defined $dateBegin && defined $dateEnd) {
                        $self->errstr("couldn't get dates from: ".$sheet_names->[$sheet_count]);
                        return undef;
                    }

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

                    $sale->productType($prodtype);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->isrc($isrc) if(defined $offsets->{isrc});
                    $sale->artistName($artist);
                    $sale->trackName($title);
                    $sale->serviceProductID($client_product_id);
                    $sale->formatType($format);
                    $sale->units($units);
                    $sale->price($price);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $sale->lineNum($linenum);

                    #$args{dumper}($sale); ## for cmd-line testing
                    $self->_insertSale(sale => $sale);
                } 
                #else { print STDERR "skip sh: ".$sheet_names->[$sheet_count] . ": l: " . $linenum . " - u:".$units." p:".$price." a:".$artist." t:".$title." f:".$format."\n"; }
                $linenum++;
            }
        }
        $sheet_count++;
    }
	return $linenum;
}

#
# Private methods
#


sub _getDates
{
    my ($month,$monthName,$year);
	my $self = shift;
	my $passed_date = shift;
    if($passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/) {
        $month = $1;
        $year = $3;
    }
    elsif($passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/) {
        $month = $2;
        $year = $1;
    }
    elsif($passed_date =~ m/Orange\s(\w+)\s(\d{2})/) {
        $monthName = $1;
        $year = $2+2000;
    }
    elsif($passed_date =~ m/(\w+)\s(\d{4})/) {
        $monthName = $1;
        $year = $2;
    }
    elsif($passed_date =~ m/(\w+)-(\d{2})-Orange/) {
        $monthName = $1;
        $year = $2+2000;
    }
    elsif($passed_date =~ m/^(\w+)\D(\d{4})$/) {
        $monthName = $1;
        $year = $2;
    }
    elsif($passed_date =~ m/(\w\w\w)\s(\d{4})/) {
        $monthName = $1;
        $year = $2;
    }
    else {
        $monthName = $passed_date;
        $passed_date =~ m/(\d{4})/;
        $year = $1;
        $monthName =~ s/\-.*$//;
    }
    $month = Decode_Month($monthName) if($month eq "" && $monthName ne "");
    #print STDERR "|->".$passed_date."<>".$monthName."<>".$month."<>".$year."<-|\n";
    my $dateBegin = sprintf("%04d-%02d-%02d", $year, $month, 1);
    my $dateEnd   = sprintf("%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month));
    return ($dateBegin, $dateEnd);
    return undef;
}

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