package RPS::Import::INGrooves3;

use strict;

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

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 = (
    7 => {
        date_begin => 0,     # A - DATE
        service    => 1,     # B - STATEMENT
        date_end   => 2,     # C - ENDING
        track      => 3,     # D - SONG
        album      => 5,     # F - ALBUM
        artist     => 6,     # G - ARTIST
        isrc       => 7,     # H - ISRC
        upc        => 8,     # I - UPC/EAN
        catalog_id => 9,     # J - CATALOG
        country    => 11,    # L - SOURCE
        units      => 12,    # M - QUANTITY
        ext_price  => 13,    # N - NET
        net_price  => 15,    # P - ROYALTY
        assettype  => 16,    # Q - ASSET TYPE
        trantype   => 18,    # S - TRANSACTION TYPE
        label      => 20,    # U - LABEL
    },

    # Version 10 is same as 7, just an extra column
    # inserted before column C
    #
    10 => {
        date_begin => 0,    # A - DATE
        service    => 1,    # B - STATEMENT

        date_end   => 3,    # D - ENDING
        track      => 4,    # E - SONG
        album      => 6,    # G - ALBUM
        artist     => 7,    # H - ARTIST
        isrc       => 8,    # I - ISRC
        upc        => 9,    # J - UPC/EAN
        catalog_id => 10,   # K - CATALOG
        country    => 12,   # M - SOURCE
        units      => 13,   # N - QUANTITY
        ext_price  => 14,   # O - NET
        net_price  => 16,   # Q - ROYALTY
        assettype  => 17,   # R - ASSET TYPE
        prodtype   => 18,   # S - PRODUCT TYPE
        trantype   => 19,   # T - TRANSACTION TYPE
        label      => 21,   # V - LABEL
    },
);

#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 );
    my $hasEuroDates;

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

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

        #------------------------------------------------------
        # Pre-scan the sheet and see if we can determine the
        # overall date format.  If any of the dates are in the
        # form DD/MM/YYYY, the we'll assume that all dates are
        # in that format.
        #------------------------------------------------------
        foreach my $line (@$sheet) {
            if (   $self->_isEuroDate( $line->[ $offsets->{date_begin} ] )
                || $self->_isEuroDate( $line->[ $offsets->{date_end} ] ) ) {
                $hasEuroDates = 1;
                last;
            }
        }

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

            if ( !$artist && !$track && !$album ) {
                $linenum++;
                next;    # skip blank lines
            }

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

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

            #if ( exists $countries{$countryName} )
            #{
            #    $countryName = $countries{$countryName};
            #}
            if ($_altName) {
                $countryName = $_altName;
            } else {
                my @countryNameArray = split( /\,/, $countryName );
                $countryName = @countryNameArray[0];
            }

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

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

            if ( $_service && $_service eq 'STATEMENT' ) {
                $linenum++;
                next;    # skip header
            }

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

            my $_assetType = $line->[ $offsets->{assettype} ];

            #----------------------------------------------------------------------
            # Per FB16283, use the PRODUCT TYPE column to determine the media type,
            # otherwise if it's blank then use the product format mappings to get
            # the media type.
            #----------------------------------------------------------------------
            my $_mediaType;
            if ( defined $offsets->{prodtype} ) {
                my $_prodType = $line->[ $offsets->{prodtype} ];
                if ($_prodType) {
                    if (   $_prodType =~ m/audio album/i
                        || $_prodType =~ m/master service tone\/ ringback tone/i
                        || $_prodType =~ m/track/i ) {
                        $_mediaType = RPS::DB::Item::MediaType::kMediaTypeAudio;
                    } elsif ( $_prodType =~ m/music video/i ) {
                        $_mediaType = RPS::DB::Item::MediaType::kMediaTypeVideo;
                    }
                }
            }

            #--------------------------------------------------------
            # 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;
                }
                $mediaType = $_mediaType if ($_mediaType);
            }

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

            my $netPrice = $line->[ $offsets->{net_price} ];
            my $extPrice = $line->[ $offsets->{ext_price} ];

            my $price = $netPrice;

            my $currency = "USD";

            if ( $units != 0 ) {

                # get the price per unit by diving by units
                $price = sprintf( "%.8f", $price / ( $units * -1 ) ) if ( $units < 0 );
                $price = sprintf( "%.8f", $price / $units ) if ( $units > 0 );

                # if the price is negative, make it positive and set units
                # to negative
                if ( $price < 0 ) {
                    $price = $price * -1;
                    $units = $units * -1 if ( $units > 0 );
                }
            }

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

            if ( $units && $price ne "" && ( $track || $album ) && $format && $catalogNumber ne 'CATALOG' ) {

                my $_dateBegin = $line->[ $offsets->{date_begin} ];
                my $_dateEnd   = $line->[ $offsets->{date_end} ];

                if ($hasEuroDates) {

                    #  DD/MM --> MM/DD
                    $_dateBegin =~ s/^(\d{2})(\D*)(\d{2})/${3}${2}${1}/;
                    $_dateEnd =~ s/^(\d{2})(\D*)(\d{2})/${3}${2}${1}/;
                }

                ( $dateBegin, $dateEnd ) = $self->_getDates(
                    date_begin => $_dateBegin,
                    date_end   => $_dateEnd,
                );

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

                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->serviceProductID($catalogNumber) if ( defined $catalogNumber );
                $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;
}

sub _isEuroDate {
    my ( $self, $date ) = @_;

    # Check for dates in the form DD/MM/YYYY.
    #
    # If a date has the form a/b/c, if the 'a' part is greater
    # than 13, then we assume that the date is DD/MM/YYYY.
    # Otherwise we assume the date is MM/DD/YYYY.
    #
    my ( $m, $d, $y ) = split( "/", $date ) if ( $date =~ m/\d{2}\/\d{2}\/\d{4}/ );

    return 1 if ( $m > 13 );
}

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