package RPS::Import::FisherPriceSheets;

use strict;

use Date::Calc qw(Days_in_Month);

use lib '/app/tools/common/lib';
use Common::Consts qw(%COUNTRY_TO_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,
    },
    3 => {
        title => 0,

        #    units       => 1,
        #    country     => 2,
        #    unitprice   => 4,
        isrc      => 1,
        units     => 3,
        country   => 4,
        unitprice => 6,
        price     => 9,
    },
);

#
# public methods
#

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

    return undef unless ($sheets);

    my $version  = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();
    my $offsets  = $field_map{$version};
    my ( $dateBegin, $dateEnd ) = _get_dates($fileName);

    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, %errors, $columns_found, %fields );
    foreach my $lines (@$sheets) {
        $columns_found = 0;
        $linenum       = 1;
        $linenum       = 6 if ( $version == 3 );
        foreach my $line (@$lines) {
            if ( $line->[0] eq "Title" && $columns_found == 0 ) {
                $columns_found = 1;
                my $x = 0;
                foreach my $column (@$line) {
                    $fields{title}   = $x if ( $column eq "Title" );
                    $fields{units}   = $x if ( $column =~ /Qty/ );
                    $fields{price}   = $x if ( $column =~ /Rate/ );
                    $fields{country} = $x if ( $column =~ /Local/ );
                    $x++;
                }
            }
            if ( $columns_found == 1 ) {
                my $artist;
                $artist = $line->[ $offsets->{artist} ] if ( defined $offsets->{artist} );
                my $isrc        = $line->[ $offsets->{isrc} ] if ( defined $offsets->{isrc} );
                my $title       = $line->[ $offsets->{title} ];
                my ($price)     = $line->[ $offsets->{price} ];
                my ($units)     = $line->[ $offsets->{units} ];
                my ($unitPrice) = $line->[ $offsets->{unitprice} ] =~ m/^(\d+\.?\d*)$/;
                $line->[ $offsets->{country} ] =~ s/\.//;
                $line->[ $offsets->{country} ] =~ s/ \(.*$//;
                my $country = $Common::Consts::COUNTRY_CODE{ lc $line->[ $offsets->{country} ] };

                if ( $title && $title !~ /title/i && $title !~ /albums/i && $price && ( $units ne "" ) ) {
                    unless ( $country || exists $errors{ $line->[ $offsets->{country} ] } ) {
                        $self->errstr( 'unknown country :' . $line->[ $offsets->{country} ] . " l: " . $linenum );
                        print STDERR "unknown country: " . $line->[ $offsets->{country} ] . " l:" . $linenum . "\n";
                        $errors{ $line->[ $offsets->{country} ] } = 1;
                    }

                    $isrc =~ s/\W+//g;
                    $price /= $units;

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

                    if ( $unitPrice > 1.5 ) {
                        $sale->productType(RPS::File::Sale::TYPE_ALBUM);
                        $sale->albumName($title);
                    } else {
                        $sale->productType(RPS::File::Sale::TYPE_TRACK);
                        $sale->trackName($title);
                    }

                    $sale->formatType($format);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->artistName($artist);
                    $sale->isrc($isrc) if ( defined $offsets->{isrc} );
                    $sale->price($price);
                    $sale->units($units);
                    $sale->countryCode($country);
                    $sale->lineNum($linenum);

                    $self->_insertSale( sale => $sale );
                }    #else { print STDERR "skip linenum:".$linenum." t:".$title." p:".$price ." u:".$units."\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.
###
