package RPS::Import::SRGIUK;

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 =
(
    237 => {
	    1 => {
            artist              => 0,
            title               => 1,
            client_product_id   => 2,
            price               => 3,
            currency            => 3,
            units               => 4,
	    },
        2 => {
            isrc                => 1,
            artist              => 2, 
            title               => 3,
            client_product_id   => 4,
            price               => 17,
            format              => 18,
            country             => 20,
            date                => 21,
            currency            => 15,
            units               => 11,
        },
    },
    238 => {
        1 => {
            isrc                => 1,
            artist              => 2,
            title               => 3,
            album               => 4,
            price               => 8,
            format              => 13,
            country             => 15,
            date                => 16,
            currency            => 11,
            units               => 17,
        },
        2 => {
            artist              => 4,
            title               => 3,
            album               => 6,
            price               => 10,
            units               => 9,
            client_product_id   => 2,
        },
    },
    239 => {
        1 => {
            isrc                => 1,
            artist              => 2,
            title               => 3,
            client_product_id   => 4,
            price               => 8,
            format              => 13,
            country             => 15,
            date                => 16,
            currency            => 11,
            units               => 17,
        },
    },
    240 => {
        1 => {
            isrc                => 1,
            artist              => 2,
            title               => 3,
            album               => 4,
            price               => 8,
            format              => 13,
            country             => 15,
            currency            => 11,
            units               => 17,
        },
        2 => {
            artist              => 1,
            title               => 2,
            price               => 7,
            units               => 3,
        },
        3 => {
            isrc                => 1,
            artist              => 2,
            title               => 3,
            album               => 4,
            price               => 10,
            format              => 13,
            country             => 15,
            currency            => 11,
            units               => 17,
        },
    },
    241 => {
        1 => {
            isrc                => 1,
            artist              => 2,
            title               => 3,
            album               => 4,
            price               => 18,
            format              => 13,
            country             => 15,
            currency            => 11,
            units               => 17,
        },
    },
    242 => {
        1 => {
            isrc                => 1,
            artist              => 2,
            title               => 3,
            album               => 4,
            price               => 10,
            format              => 13,
            country             => 15,
            currency            => 11,
            units               => 17,
            date                => 16,
        },
    },
    243 => {
        1 => {
            isrc                => 1,
            artist              => 2,
            title               => 3,
            client_product_id   => 4,
            price               => 9,
            #exchange            => 12,
            format              => 13,
            country             => 15,
            currency            => 11,
            units               => 17,
            date                => 16,
        },
    },
    244 => {
        1 => {
            isrc                => 1,
            artist              => 2,
            title               => 3,
            client_product_id   => 4,
            price               => 10,
            exchange            => 12,
            format              => 13,
            country             => 15,
            currency            => 11,
            units               => 17,
        },
    },
);

#public methods

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

	my $fileObj = $args{file};
    my $version = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();
    my $serviceID = $args{file}->ServiceID;
    #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{$serviceID}{$version};
    my $sheet_names = $args{sheet_names};
    my $header_found = 0;
    my $linenum = 1;
    my %prices;
    my $tax_rate = 0;
    my ($dateBegin,$dateEnd,$album,$country,$client_product_id,$format,$isrc,$units,$prodtype,$currency,$price,$exchange_rate);
    my $mediaType;

    foreach my $sheet(@{ $args{sheets} }) {
        my $linenum = 1;
        $linenum = 2 if($serviceID==238 && $version==2);
        if($sheet_names->[$sheet_count] =~ /summary/i) {
            foreach my $line(@$sheet) {
                if($line->[0] =~ /tax/i) {
                    $line->[0] =~ m/\((\d+)\%\)/;
                    $tax_rate = ((100-$1)/100) if($1 ne "");
                }
            }
        }
        elsif($sheet_names->[$sheet_count] !~ /form/i && $sheet_names->[$sheet_count] !~ /summary/i && $sheet_names->[$sheet_count] !~ /^(\d{4})\.(\d+)\-(\d+)/) {
            ($dateBegin, $dateEnd) = $self->_getDates($sheet_names->[$sheet_count]."-".$fileName) if($offsets->{date} eq "" && $sheet_names->[$sheet_count] !~ /sheet/i);
            ($dateBegin, $dateEnd) = $self->_getDates($fileName) if($serviceID == 244);

            foreach my $line (@$sheet) {
                my $artist           = $line->[$offsets->{artist}];
                my $title            = $line->[$offsets->{title}];
                $country             = $line->[$offsets->{country}] if(defined $offsets->{country});
                $client_product_id   = $line->[$offsets->{client_product_id}] if(defined $offsets->{client_product_id});
                $format              = $line->[$offsets->{format}] if(defined $offsets->{format}); 
                $prodtype            = RPS::File::Sale::TYPE_TRACK;
                $units               = $line->[$offsets->{units}] if (defined $offsets->{units});
                $price               = $line->[$offsets->{price}];
                $currency            = uc $line->[$offsets->{currency}];
                $isrc                = $line->[$offsets->{isrc}] if (defined $offsets->{isrc});
                $album               = $line->[$offsets->{album}] if (defined $offsets->{album});
                $exchange_rate       = $line->[$offsets->{exchange}] if (defined $offsets->{exchange});
                if($serviceID == 244 && $exchange_rate ne "") {
                    $price           *= (1/$exchange_rate) if($exchange_rate != 0);
                    $currency        = "EUR";
                }
                if($serviceID == 240 && $version==3) {
                    $price = $line->[$offsets->{price} - 2] if($price eq "");
                }
                if($serviceID == 240 && $version==2) {
                    $country = "JP";
                    $currency = "USD";
                    $format = RPS::File::Sale::FORMAT_DOWNLOAD;
                }
                if($serviceID == 241 && $price eq "") {
                    if($units%120==0) {
                        $price = $units;
                        $units /= 120;
                    }
                    elsif($units%50==0) {
                        $price = $units;
                        $units /= 50;
                    }
                }
                $price = 150 if($serviceID == 243 && $price eq "");
                $format = "pdl" if($format eq "" && $serviceID == 243);
                $format = "pdl" if($serviceID==238 and $version==2);
                $country = "JP" if($serviceID==238 and $version==2);
                $country = "JP" if($country =~ /japan/i);
                $country = "CN" if($country =~ /china/i);
                $country = "JP" if($country eq "" && $serviceID == 243);
                $currency = "JPY" if($currency =~ /yen/i);
                $currency = "USD" if($currency =~ /us/i);
                $currency = "CNY" if($currency =~ /cny/i);
                $currency = "JPY" if($currency eq "" && ($serviceID == 243 || $serviceID == 238 || $serviceID == 240));
                $price =~ s/yen//i;
                $price =~ s/\s//g;
                $price *= .5 if ($version==1 && $serviceID == 237);
                $price /= $units if($units>0 && $price>0 && ($version > 1 || $serviceID != 237 && $serviceID != 243));
                $price *= $tax_rate if($serviceID == 241);

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

                $format = RPS::File::Sale::FORMAT_TETHERED if($format =~ /tdl/i);
                $format = RPS::File::Sale::FORMAT_DOWNLOAD if($format =~ /pdl/i);
                $format = RPS::File::Sale::FORMAT_STREAM if($format =~ /str/i);
                $format = RPS::File::Sale::FORMAT_RINGBACK if($format =~ /rbt/i);

                if($format =~ /vid/i)
                {
                    $format = RPS::File::Sale::FORMAT_DOWNLOAD; # was FORMAT_VIDEO (FB1324)
                    $mediaType = RPS::DB::Item::MediaType::kMediaTypeVideo;
                }
                #$format = RPS::File::Sale::FORMAT_GRAPHIC if($format =~ /img/i); # Retired (FB1324)

                $format = RPS::File::Sale::FORMAT_RINGTONE if($format =~ /ppc/i);
                $format = RPS::File::Sale::FORMAT_RINGTONE if($format =~ /mpc/i);
                $format = RPS::File::Sale::FORMAT_RINGTONE if($format =~ /cu/i);

                if ($units && $price && $title && $format && $title !~ /title/i && $title ne "4" && $title ne "Total" && ($dateBegin ne "" || $line->[$offsets->{date}] ne "")) {
                    ($dateBegin, $dateEnd) = $self->_getDates($line->[$offsets->{date}]) if(defined $offsets->{date} && $line->[$offsets->{date}] ne "");

                    unless (defined $dateBegin && defined $dateEnd) {
                        #print STDERR $dateBegin."<>".$dateEnd."\n";
                        $self->errstr("couldn't get dates from: ".$fileName."-".$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) if(defined $offsets->{client_product_id});
                    $sale->albumName($album) if(defined $offsets->{album});
                    $sale->formatType($format);
                    $sale->mediaType($mediaType);
                    $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);
                    #print STDERR "insert sh:".$sheet_names->[$sheet_count] . " l:".$linenum . " a:".$artist." t:".$title." u:".$units." p:".$price ." r:".$exchange_rate."|->\n";
                } 
                #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;
    #print STDERR "X>".$passed_date."<X\n";

    if($passed_date =~ /060811/) {
        $month = 6;
        $year = 2006;
    }
    if($passed_date =~ m/2(\d{3})/ && $passed_date !~ m/(\d{4})\D(\d+)\D(\d)/ && $passed_date !~ m/(\d+)\D(\d+)\D(\d{4})/) {
        $year = "2".$1;
        if($passed_date =~ m/(\d{4})(\d\d)(\d\d)/) {
            $year = $1;
            $month = $2;
        }
        elsif($passed_date =~ m/(\d{4})\.(\d+)/) {
            $year = $1;
            $month = $2;
        }
    }
    elsif($passed_date =~ m/(\d{4})\.(\d+)/) {
        $year = $1;
        $month = $2;
    }
    elsif($passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/) {
        $year = $1;
        $month = $2;
    }
    elsif($passed_date =~ m/(\d{4})\s(\w+)/) {
        $year = $1;
        $monthName = $2;
    }
    elsif($passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/) {
        $year = $3;
        $month = $1;
    }
    elsif($passed_date =~ m/(\d{4})(\d\d)(\d\d)/) {
        $year = $1;
        $month = $2;
    }
    if($month eq "") {
        $monthName = "jan" if($passed_date =~ /jan/i);
        $monthName = "feb" if($passed_date =~ /feb/i);
        $monthName = "mar" if($passed_date =~ /mar/i);
        $monthName = "apr" if($passed_date =~ /apr/i);
        $monthName = "may" if($passed_date =~ /may/i);
        $monthName = "jun" if($passed_date =~ /jun/i);
        $monthName = "jul" if($passed_date =~ /jul/i);
        $monthName = "aug" if($passed_date =~ /aug/i);
        $monthName = "sep" if($passed_date =~ /sep/i);
        $monthName = "oct" if($passed_date =~ /oct/i);
        $monthName = "nov" if($passed_date =~ /nov/i);
        $monthName = "dec" if($passed_date =~ /dec/i);
        $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.
###
