package RPS::Import::FisherPrice;

use strict;

use Date::Calc qw(Days_in_Month);

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

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

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

my %field_map = (
    1 => {
        title       => 0,
        artist      => 1,
        isrc        => 2,
        unitprice   => 3,
        units       => 4,
        country     => 5,
        price       => 10,
    },
    2 => {
        title       => 0,
        isrc        => 1,
        unitprice   => 2,
        units       => 3,
        country     => 4,
        price       => 9,
    },
    4 => {
        title       => 0,
        unitprice   => 4,
        units       => 5,
        country     => 6,
        price       => 11,
    },
    5 => {
        grand_total_col => 0,
        title       => 0,
        unitprice   => 4,
        units       => 5,
        country     => 6,
        price       => 11,
    },
    6 => {
        title       => 0,
        artist      => 1,
        upc         => 2,
        isrc        => 3,
        unitprice   => 4,
        units       => 5,
        country     => 6,
        price       => 11,
    },      
);

#
# public methods
#

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

    return undef unless ($lines);
    my $version = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();
    my @sheets = @{ $args{sheets} };
    #my $version = $args{version}; # cmd-line testing
    #my $fileName = $args{OrigFileName};

    my $offsets = $field_map{$version};
    my ($dateBegin, $dateEnd) = _get_dates($fileName);
    my $grandTotal = 0;
    my $runningTotal = 0;

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

    my $format = RPS::File::Sale::FORMAT_DOWNLOAD;
    my $linenum;
    my $sheetnum = 0;
    my %errors;
    $linenum = 3 if($version==2);
    
    foreach my $sheet (@sheets){  
        $sheetnum++;           
       if($version == 2){
           $linenum = 3;
       }
       elsif($version == 5){
           $linenum = 2;
       }
       else{
           $linenum = 1;
       }
       
       if(($runningTotal > 0) && (sprintf("%.2f",$runningTotal) == $grandTotal)){
           return $linenum;
       }   
    
    foreach my $line (@$sheet)
    {

        my $artist         = $line->[$offsets->{artist}] if (defined $offsets->{artist});
        my $isrc        = $line->[$offsets->{isrc}] if (defined $offsets->{isrc});
        my $upc         = $line->[$offsets->{upc}] if (defined $offsets->{upc});
        my $title       = $line->[$offsets->{title}];
        my $price       = $self->numeric($line->[$offsets->{price}]);
        my $units       = $self->numeric($line->[$offsets->{units}]);
        my ($unitPrice) = $line->[$offsets->{unitprice}] =~ m/^(\d+\.?\d*)$/;
        $line->[$offsets->{country}] =~ s/\.//;
        
        if($line->[$offsets->{grand_total_col}] =~ /grand total/i){
            $grandTotal = $line->[$offsets->{grand_total_col} + 1];
            print STDERR "Found grand total $grandTotal\n";
            $grandTotal = sprintf("%.2f",$grandTotal);
        }
        
        my $country     = $COUNTRY_CODE{lc $line->[$offsets->{country}] };
        if ($title && $title ne 'Total:' && $price && $units)
        {
            unless ($country || exists $errors{$line->[$offsets->{country}]})
            {
                $self->errstr('unknown country');
                print STDERR "unknown country: $line->[$offsets->{country}], line: $linenum\n";
                $errors{$line->[$offsets->{country}]} = 1;
            }          
            
            $runningTotal += $price;
            
            $isrc =~ s/\W+//g;
            $price /= $units;

            my $albumTitle;
            my $trackTitle;
            my $productType;
            
            if ($version == 6)
            {
                if ($upc)
                {
                    $productType = RPS::File::Sale::TYPE_ALBUM;
                    $albumTitle = $title;                    
                }
                else
                {
                    $productType = RPS::File::Sale::TYPE_TRACK;
                    $trackTitle = $title;                    
                }            
            }
            else
            {
                if ($unitPrice > 1.5)
                {
                    $productType = RPS::File::Sale::TYPE_ALBUM;
                    $albumTitle = $title;
                }
                else
                {
                    $productType = RPS::File::Sale::TYPE_TRACK;
                    $trackTitle = $title;
                }   
            }         


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

            $sale->albumName($albumTitle);
            $sale->trackName($trackTitle);
            $sale->productType($productType);
            $sale->formatType($format);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->artistName($artist);
            $sale->isrc($isrc) if ($version != 4);
            $sale->upc($upc);
            $sale->price($price);
            $sale->units($units);
            $sale->countryCode($country);
            $sale->lineNum($linenum);

            #$args{dumper}($sale); ## for cmd-line testing
            $self->_insertSale(sale => $sale);
        } #else { print STDERR "skip linenum:".$linenum." : ". join('|', @$line) . "\n"; }
        $linenum++;
    }
    }
    return $linenum;
}

#
# Private methods
#

sub _get_dates
{
    my $fileName = shift;
    my ($month1, $day1, $year1, $month2, $day2, $year2);
    if($fileName =~ /from/) {
         my ($start_date,$end_date) = split(" through ",$fileName);
         $start_date =~ s/^.*from //;
         $end_date =~ s/_.*$//;
         ($month1,$day1,$year1) = split("-",$start_date);
         ($month2,$day2,$year2) = split("-",$end_date);
         return undef unless ($month1 && $year1 && $month2 && $year2);
    }
    elsif ($fileName =~ m/(\d)Q(\d+)/) {
        my $qtr = $1;
        my $year = $2+2000;
        $year1 = $year;
        $year2 = $year;
        if ($qtr == 1) {
            $month1 = "01";
            $month2 = "03";
        } elsif ($qtr == 2) {
            $month1 = "04";
            $month2 = "06";
        } elsif ($qtr == 3) {
            $month1 = "07";
            $month2 = "09";
        } elsif ($qtr == 4) {
            $month1 = "10";
            $month2 = "12";
        }
    }
    else {
        return undef unless ($fileName =~ m/for\D+(\d+)\D+\d+\D+(\d{4})\D+(\d+)\D+\d+\D+(\d{4})/);
        ($month1, $year1, $month2, $year2) = ($1, $2, $3, $4);
    }
    return (
        sprintf("%04d-%02d-01", $year1, $month1), 
        sprintf("%04d-%02d-%02d", $year2, $month2, Days_in_Month($year2, $month2))
    );
}

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