package RPS::Import::INGrooves::Base;

use strict;

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

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

use base 'RPS::Import::INGroovesBase';

#public methods

sub _getDateFromSheet
{
    my $self = shift;
    my $sheetName = @_;
    # override this if you want to extract date from a specific sheet
    # otherwise the date will be determined on a line-by-line basis
    return undef;
}

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 = $self->_fieldMap;

    my $sheet_names = $args{sheet_names};
    my $_numsheets = (scalar @{$sheet_names});

    my $header_found = 0;
    my $linenum = 1;
    my %prices;
    my ($dateBegin,$dateEnd);
    my $useGlobalDate;

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

        my $currentSheetName = $sheet_names->[$sheet_count];

        #
        # The sale dates can be determined from a specific sheet and used
        # globally for all sales, or they can be determined from each
        # individual sales line.
        #
        if ( !$dateBegin && !$dateEnd && $self->_getDateFromSheet( $currentSheetName ) )
        {
            foreach my $line (@$sheet)
            {
                my $dlabel = $line->[$offsets->{date_begin}-1];
                my $dt = $line->[$offsets->{date_begin}];
                if ( !$dateBegin && !$dateEnd && $dlabel && $dlabel =~ m/date\:/i )
                {
                    ($dateBegin, $dateEnd) = $self->_getDates( date_begin=>$dt );
                    $useGlobalDate = 1;
                }
            }
        }

        if ( ( !$currentSheetName && $_numsheets == 0 ) ||
             ( $currentSheetName && $currentSheetName =~ /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 = $line->[$offsets->{prodtype}];

                #----------------------------------------------------------
                # 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) {

                    if ( !$useGlobalDate )
                    {
                        ($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;
                    }

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

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

                    $sale->serviceProductID($catalogNumber) if ( $catalogNumber );
                    $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.
###
