package RPS::Import::HDTracks;

use strict;
use warnings;

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

use constant RE_FLOAT => qr/^[+-]?(\d*[.])?\d+$/;

my %fieldMap = (
    1 => {
        upc     => 2,
        isrc    => 3,
        label   => 7,
        artist  => 8,
        track   => 9,
        album   => 10,
        units   => 11,
        price   => 14,
        product => 13,
    },
    2 => {
        upc     => 2,
        isrc    => 3,
        label   => 7,
        artist  => 8,
        track   => 9,
        album   => 10,
        units   => 11,
        price   => 14,
        product => 13,
        sacd    => 15,
    },
    3 => {
        date_col => 0,
        date_row => 0,
        upc      => 0,
        isrc     => 1,
        label    => 5,
        artist   => 6,
        track    => 7,
        album    => 8,
        units    => 9,
        product  => 11,
        price    => 12,
        sacd     => 13,
    },
    4 => {
        date_begin => 0,  # A
        date_end   => 1,  # B
        upc        => 2,  # C
        isrc       => 4,  # E
        label      => 6,  # G
        artist     => 7,  # H
        track      => 8,  # I
        album      => 9,  # J
        units      => 10, # K
        price      => 13, # N
        product    => 12, # M
    },
);

my %product_map = (
    albums  => RPS::File::Sale::TYPE_ALBUM,
    album  => RPS::File::Sale::TYPE_ALBUM,
    bundles => RPS::File::Sale::TYPE_ALBUM,
    tracks  => RPS::File::Sale::TYPE_TRACK,
    track  => RPS::File::Sale::TYPE_TRACK,
);

sub _importLines {
    my $self        = shift;
    my %args        = @_;
    my $fileObj     = $args{file};
    my $lines       = $args{lines};
    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 );

    if ( ( defined $offsets->{date_row} ) && ( defined $offsets->{date_col} ) ) {
        my ( $f_date_begin, $f_date_end ) =
          split( "thru", $lines->[ $offsets->{date_row} ]->[ $offsets->{date_col} ] );

        ( $dateBegin, $dateEnd ) = $self->SUPER::_getDates( date_begin => $f_date_begin, date_end => $f_date_end );
    }

    unless ( $dateBegin && $dateEnd ) {
        ( $dateBegin, $dateEnd ) = _getDates($fileName);
    }

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

            foreach my $line (@$sheet) {
                my $free     = 0;
                my $country  = "US";
                my $currency = "USD";
                my $artist   = $line->[ $offsets->{artist} ];
                my $track    = $line->[ $offsets->{track} ];
                my $album    = $line->[ $offsets->{album} ];
                my $format   = RPS::File::Sale::FORMAT_DOWNLOAD;
                my $product  = $product_map{ lc($line->[ $offsets->{product} ] || '') };
                my $units    = $line->[ $offsets->{units} ] || 0;
                my $upc      = $line->[ $offsets->{upc} ];
                my $isrc     = $line->[ $offsets->{isrc} ];
                my $price    = $line->[ $offsets->{price} ] || 0;
                my $label    = $line->[ $offsets->{label} ];
                my $catalog  = $line->[ $offsets->{catalog} ] if $offsets->{catalog};
                $dateBegin   = $line->[ $offsets->{date_begin} ];
                $dateEnd     = $line->[ $offsets->{date_end} ];

                $price =~ s/,//g;
                unless ( $price =~ RE_FLOAT && $units =~ RE_FLOAT ) {
                    print STDERR "Invalid format of units: '$units' or price: '$price'. Skip the line $linenum.\n";
                    next;
                }

                $price /= $units if ( $units != 0 );
                $free = 1 if ( $price == 0 );

                if ( $units && ( $track || $album ) && $track !~ /Track Title/i ) {

                    unless ( defined $dateBegin && defined $dateEnd ) {
                        print STDERR "Couldn't get dates from: " . $fileName . "\n";
                        $self->errstr( "couldn't get dates from: " . $fileName );
                        return undef;
                    }
                    unless ( $format ne "" ) {
                        print STDERR "Couldn't get format for: " . $line->[ $offsets->{format} ] . "(" . $linenum . ")\n";
                        $self->errstr( "Couldn't get format for: " . $line->[ $offsets->{format} ] . "(" . $linenum . ")" );
                        return undef;
                    }
                    unless ( $product =~ /(A|T)/ ) {
                        print STDERR "Couldn't get get product for: " . $line->[ $offsets->{product} ] . "(" . $linenum . ")\n";
                        $self->errstr( "Couldn't get get product for: " . $line->[ $offsets->{product} ] . "(" . $linenum . ")" );
                        return undef;
                    }

                    #if (defined $offsets->{sacd})
                    #{
                    # We don't want to import the file if this column is set to yes
                    # because we don't have anything in place to handle SACD royalties.
                    #
                    #     my $sacdTest = $line->[$offsets->{sacd}];
                    #     if (lc($sacdTest) ne 'no')
                    #     {
                    #          print STDERR "96/24 column set to: ".
                    #          $line->[$offsets->{sacd}] . "(".$linenum.")\n";
                    #          $self->errstr("96/24 column set to: ".
                    #          $line->[$offsets->{sacd}] . "(".$linenum.")");
                    #          return undef;
                    #     }
                    # }

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

                    $sale->mediaType(2) if ( $format =~ /video/i );
                    $sale->productType($product);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->artistName($artist);
                    $sale->labelName($label);
                    $sale->trackName($track);
                    $sale->albumName($album);
                    $sale->upc($upc);
                    $sale->isrc($isrc) if ( $isrc ne "" );
                    $sale->formatType($format);
                    $sale->units($units);
                    $sale->price($price);
                    $sale->free($free);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $sale->lineNum($linenum);

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

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

#
# Private methods
#

sub _getDates {
    my ( $smonth, $syear, $sday, $emonth, $eyear, $eday );
    my $passed_date = shift;
    if ( $passed_date =~ m/_(\d{4})-(\d+)-(\d+)_to_(\d{4})-(\d+)-(\d+)/ ) {
        $syear  = $1;
        $smonth = $2;
        $sday   = $3;
        $eyear  = $4;
        $emonth = $5;
        $eday   = $6;
    } elsif ( $passed_date =~ m/_(\d+)_(\d+)_(\d{4})_(\d+)_(\d+)_(\d{4})/ ) {
        $syear  = $3;
        $smonth = $1;
        $sday   = $2;
        $eyear  = $6;
        $emonth = $4;
        $eday   = $5;
    }
    if ( $syear && $eyear && $smonth && $emonth && $sday && $eday ) {
        return ( $syear . "-" . $smonth . "-" . $sday, $eyear . "-" . $emonth . "-" . $eday );
    }
    return undef;
}

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