package RPS::Import::State51;

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

my %fieldMap = (
    1 => {
        service    => 1,
        start_date => 2,
        end_date   => 3,
        currency   => 4,
        artist     => 6,
        title      => 7,
        label      => 8,
        upc        => 10,
        catalog    => 11,
        isrc       => 12,
        unitsa     => 16,
        unitsb     => 17,
        unitsc     => 18,
        price      => 67,

    },
);

#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 $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 ( $dateBegin, $dateEnd );

    foreach my $sheet ( @{ $args{sheets} } ) {
        $linenum = 1;
        if ( $sheet_names->[$sheet_count] =~ /full ext/i ) {

            foreach my $line (@$sheet) {
                my $country = "GB";

                #my $currency            = $line->[$offsets->{currency}];
                my $currency    = "GBP";
                my $product     = RPS::File::Sale::TYPE_TRACK;
                my $artist      = $line->[ $offsets->{artist} ];
                my $catalog     = $line->[ $offsets->{catalog} ];
                my $serviceName = $line->[ $offsets->{service} ];
                my $isrc        = $line->[ $offsets->{isrc} ];
                my $upc         = $line->[ $offsets->{upc} ];
                my $label       = $line->[ $offsets->{label} ];
                my $title       = $line->[ $offsets->{title} ];
                my $format      = RPS::File::Sale::FORMAT_DOWNLOAD;
                my $units       = $line->[ $offsets->{unitsa} ] + $line->[ $offsets->{unitsb} ] + $line->[ $offsets->{unitsc} ];
                my $price       = $line->[ $offsets->{price} ];
                $isrc =~ s/\-//g;
                $upc =~ s/\-//g;
                $price /= $units if ( $units != 0 );

                if ( $units && $country && $price && $title && $title ne "Title" ) {
                    $serviceName =~ s/Juno Digital/Juno/;
                    $serviceName =~ s/Bleep.com/WarpBleep/;
                    $serviceName =~ s/trackitdown/track it down/i;
                    $serviceName =~ s/Traxsource/trax source/i;

                    my $service_id = $self->getServiceID( lc($serviceName) );

                    $dateBegin = _getDates( $line->[ $offsets->{start_date} ] );
                    $dateEnd   = _getDates( $line->[ $offsets->{end_date} ] );

                    unless ( defined $dateBegin && defined $dateEnd ) {
                        print STDERR "Couldn't get dates from: " . $sheet->[ $offsets->{date_start_row} ]->[ $offsets->{date_col} ] . "\n";
                        $self->errstr( "couldn't get dates from: " . $sheet->[ $offsets->{date_end_row} ]->[ $offsets->{date_col} ] );
                        return undef;
                    }

                    unless ($service_id) {
                        print STDERR "Unknown service: " . $line->[ $offsets->{service} ] . " (" . $linenum . ")\n";
                        $self->errstr( "Unknown service: " . $line->[ $offsets->{service} ] . " (" . $linenum . ")" );
                        return undef;
                    }

                    $product = RPS::File::Sale::TYPE_ALBUM if ( $isrc eq "" );
                    my $sale = RPS::Import::SaleRec->new();

                    $sale->mediaType(2) if ( $format =~ /video/i );
                    $sale->productType($product);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->isrc($isrc) if ( $isrc ne "" );
                    $sale->upc($upc) if ( $upc ne "" && $upc ne "_DM" );
                    $sale->serviceID($service_id);
                    $sale->serviceProductID($catalog);
                    $sale->artistName($artist);
                    $sale->trackName($title) if ( $product eq RPS::File::Sale::TYPE_TRACK );
                    $sale->albumName($title) if ( $product eq RPS::File::Sale::TYPE_ALBUM );
                    $sale->labelName($label);
                    $sale->formatType($format);
                    $sale->units($units);
                    $sale->price($price);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $sale->lineNum($linenum);

                    $self->_insertSale( sale => $sale );
                }

#else { print STDERR "skip sh: ".$sheet_names->[$sheet_count] . ": l: " . $linenum . " - c:".$country." u:".$units." p:".$price." c:".$catalog." t:".$track." f:".$format."\n"; }
                $linenum++;
            }
        }
        $sheet_count++;
    }
    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my ( $year, $month, $day, $monthName, $qtr, $passed_date, $dateBegin, $dateEnd );
    $passed_date = shift;
    $passed_date =~ s/\s.*$//;

    #print STDERR "|>".$passed_date."<|\n";
    if ( $passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/ ) {
        $year  = $1;
        $month = $2;
        $day   = $3;
    } elsif ( $passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/ ) {
        $year  = $3;
        $month = $1;
        $day   = $2;
    }
    if ( $year && $month && $day ) {
        return ( $year . "-" . sprintf( "%02d", $month ) . "-" . sprintf( "%02d", $day ) );
    }

    return undef;
}

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