package RPS::Import::INGrooves2;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days Decode_Month);

use lib '/app/tools/common/lib';
use Common::Country;

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

# map version num to the field order
my %fieldMap = (
    1 => {
        date_begin => 0,
        service    => 1,
        date_end   => 2,
        track      => 3,
        album      => 4,
        artist     => 6,
        isrc       => 7,
        upc        => 8,
        country    => 11,
        units      => 12,
        price      => 16,
    },
    2 => {
        date_begin => 0,
        service    => 1,
        date_end   => 2,
        track      => 3,
        album      => 5,
        artist     => 6,
        isrc       => 7,
        upc        => 8,
        country    => 11,
        units      => 12,
        price      => 16,
    },

    # case 10994 - versions 3 and 4 have been deactivated
    5 => {
        date_begin => 0,
        service    => 1,
        date_end   => 2,
        track      => 3,
        album      => 4,
        artist     => 6,
        isrc       => 7,
        upc        => 8,
        country    => 10,
        units      => 11,
        price      => 15,
    },
    6 => {
        date_begin  => 0,
        service     => 1,
        date_end    => 2,
        track       => 3,
        album       => 5,
        artist      => 6,
        isrc        => 7,
        upc         => 8,
        country     => 11,
        units       => 12,
        price       => 14,
        prodtype    => 15,
        altprodtype => 16,
        label       => 19,
    },
);

#public methods

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

    my $fileObj     = $args{file};
    my $version     = $args{file}->VersionNum();
    my $fileName    = $args{file}->OrigFileName();
    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 %prices;
    my ( $dateBegin, $dateEnd );

    foreach my $sheet ( @{ $args{sheets} } ) {
        my $linenum = 1;

        if ( $sheet_names->[$sheet_count] =~ /details/i ) {

            foreach my $line (@$sheet) {
                my $artist = $line->[ $offsets->{artist} ];
                my $track  = $line->[ $offsets->{track} ];
                my $album  = $line->[ $offsets->{album} ];

                my $countryName = $line->[ $offsets->{country} ];

                # Seeing lots of country names
                #
                my @countryNameArray = split( /\,/, $countryName );
                $countryName = @countryNameArray[0];

                my $isrc = $line->[ $offsets->{isrc} ];
                my $upc  = $line->[ $offsets->{upc} ];

                my $_service = $line->[ $offsets->{service} ];

                my $_assetType;

                if ( defined $offsets->{prodtype} ) {
                    $_assetType = $line->[ $offsets->{prodtype} ];
                } else {
                    #
                    # Versions 1, 2 and 5 don't have an 'asset type' (or product type) column,
                    # If a line has a track title andor ISRC then it's assumed to be a track.
                    # If a line has an album title and/or UPC then it's assumed to be an album.
                    # so we need to determine the asset type by looking at the ISRC and UPC
                    #
                    if ( ( $isrc && $isrc !~ m/^isrc$/i ) || ( $track && $track !~ m/^track$/i ) ) {
                        $_assetType = 'track';
                    } elsif ( ( $upc && $upc !~ m/^upc\/ean$/i ) || ( $album && $album !~ m/^album$/i ) ) {
                        $_assetType = 'album';
                    }

                }

                #----------------------------------------------------------
                # Per FB14063, we strip off any trailing country code data.
                #----------------------------------------------------------
                $_service =~ s/ (\w{3})$//;

                #--------------------------------------------------------
                # lookup the service, format, product type and media type
                # information using the information in the STATEMENT and
                # ASSET TYPE columns.
                #--------------------------------------------------------
                my ( $serviceID, $format, $prodtype, $mediaType );
                if ( $_service && $_service !~ m/STATEMENT/i && $_assetType ) {
                    ( $serviceID, $format, $prodtype, $mediaType ) = $self->_getServiceFormat( $_service, $_assetType );

                    if ( !$format ) {
                        $self->errstr("Unable to determine format from '$_service' on line $linenum");
                        return undef;
                    }
                }

                my $label = $line->[ $offsets->{label} ] if ( defined $offsets->{label} );

                my $units = $line->[ $offsets->{units} ] if ( defined $offsets->{units} );
                my $price = $line->[ $offsets->{price} ];

                my $currency = "USD";

                if ( $units != 0 ) {
                    $price = sprintf( "%.8f", $price / ( $units * -1 ) ) if ( $units < 0 );
                    $price = sprintf( "%.8f", $price / $units )          if ( $units > 0 );
                    $price = sprintf( "%.8f", $price * -1 )              if ( $price < 0 );
                }

                my $free = ( $price == 0 ) ? 1 : 0;

                if ( $units && $price ne "" && ( $track || $album ) && $format && $track !~ /^title$/i && $track !~ /^song$/i ) {

                    ( $dateBegin, $dateEnd ) =
                      $self->_getDates( date_begin => $line->[ $offsets->{date_begin} ], date_end => $line->[ $offsets->{date_end} ] );

                    unless ( defined $countryName ) {
                        $self->errstr("Missing country on line $linenum");
                        return undef;
                    }

                    my $_altName = $self->_getAlternateCountryName($countryName);

                    if ($_altName) {
                        $countryName = $_altName;
                    }

                    my $countryObj = Common::Country->Get($countryName);
                    my $country = $countryObj->alpha2 if ($countryObj);

                    unless ( defined $dateBegin && defined $dateEnd ) {
                        $self->errstr("Couldn't get dates from line $linenum");
                        return undef;
                    }

                    unless ( defined $serviceID ) {
                        $self->errstr("Unrecognized service on line $linenum: $_service");
                        return undef;
                    }

                    unless ( defined $country ) {
                        $self->errstr("Unrecognized country on line $linenum: $countryName");
                        return undef;
                    }

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

                    $sale->productType($prodtype);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->artistName($artist);
                    $sale->trackName($track) if ( $prodtype eq RPS::File::Sale::TYPE_TRACK );
                    $sale->albumName($album) if ( defined $album && $album ne "" );
                    $sale->upc($upc)         if ( defined $upc );
                    $sale->isrc($isrc)       if ( defined $isrc );
                    $sale->labelName($label) if ( defined $label );
                    $sale->serviceID($serviceID);
                    $sale->formatType($format);
                    $sale->units($units);
                    $sale->price($price);
                    $sale->free($free);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $sale->mediaType($mediaType);
                    $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;
}

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