package RPS::Import::TurnTableLab::v6;

use strict;

use Date::Calc qw(Days_in_Month);

use lib '/app/tools/data_classes/lib';

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

my %field_map = (
    6 => {
        label          => 0,
        isrc           => 1,
        upc            => 2,
        artist         => 3,
        title          => 4,
        catalog_number => 5,
        prod_type      => 6,
        units          => 7,
        price          => 10,
        format         => 12,
        country        => 13,
        sale_date      => 14,
        currency       => 15,
        mechanicals    => 17,
    },
);

my %delivery_formats = (
    'DOWNLOAD'              => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Stream'                => RPS::File::Sale::FORMAT_STREAM,
    'Limited Download'      => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Over the Air Download' => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Ringtone'              => RPS::File::Sale::FORMAT_RINGTONE,
    'Ringback'              => RPS::File::Sale::FORMAT_RINGBACK,
    'Over the Air Download' => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Burn'                  => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Other'                 => RPS::File::Sale::FORMAT_STREAM,
    'Play'                  => RPS::File::Sale::FORMAT_STREAM,
    'Realtone'              => RPS::File::Sale::FORMAT_RINGTONE,
);

#
# public methods
#

sub _importLines {
    my $self  = shift;
    my %args  = @_;
    my $lines = $args{lines};
    return undef unless ($lines);
    my $version = $self->_version();
    my $offsets = $field_map{$version};

    #my $fileName = $args{OrigFileName}; # cmd-line testing
    my $fileName = $args{file}->OrigFileName();

    my $linenum         = 1;
    my $was_album_title = 0;
    my ( %errors, $passed_format, $album, $dateBegin, $dateEnd, $total_columns, $fee_percentage );
    ( $dateBegin, $dateEnd ) = _get_dates($fileName) unless ( exists $offsets->{sale_date} );

    foreach my $line (@$lines) {
        my ( $artist, $country, $isrc, $title, $upc, $price, $currency_code, $format, $units, $label, $service_product, $prod_type );
        $artist        = $line->[ $offsets->{artist} ];
        $isrc          = $line->[ $offsets->{isrc} ];
        $title         = $line->[ $offsets->{title} ];
        $album         = $line->[ $offsets->{album} ] if exists $offsets->{album};
        $upc           = $line->[ $offsets->{upc} ];
        $price         = $line->[ $offsets->{price} ];
        $country       = exists $offsets->{country} ? $line->[ $offsets->{country} ] : 'US';
        $currency_code = exists $offsets->{currency_code} ? $line->[ $offsets->{currency_code} ] : 'USD';
        $format        = exists $offsets->{format} ? $delivery_formats{ $line->[ $offsets->{format} ] } : RPS::File::Sale::FORMAT_DOWNLOAD;
        $units         = $line->[ $offsets->{units} ];
        $label         = $line->[ $offsets->{label} ];
        $service_product = $line->[ $offsets->{catalog_number} ] if exists $offsets->{catalog_number};

        $prod_type = $line->[ $offsets->{prod_type} ] =~ /^a/i ? RPS::File::Sale::TYPE_ALBUM : RPS::File::Sale::TYPE_TRACK;

        $album = $line->[ $offsets->{title} ] if ( $prod_type eq RPS::File::Sale::TYPE_ALBUM );

        if ( ( $artist ne "TRACK_ARTIST" ) && ( $units > 0 ) && ( $title ne "" ) ) {

            ( $dateBegin, $dateEnd ) = _get_dates( $line->[ $offsets->{sale_date} ] ) if ( exists $offsets->{sale_date} );

            unless ( $dateBegin ne "" && $dateEnd ne "" ) {
                $self->errstr( "Couldn't get dates from: " . $line->[ $offsets->{sale_date} ] . " l:" . $linenum . " or " . $fileName );
                print STDERR "Couldn't get dates from:" . $line->[ $offsets->{sale_date} ] . " l:" . $linenum . " or " . $fileName . "\n";
            }

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

            $sale->productType($prod_type);
            $sale->upc($upc);
            $sale->isrc($isrc)       if ( $isrc ne "" );
            $sale->trackName($title) if ( $prod_type eq RPS::File::Sale::TYPE_TRACK && $title ne "ALBUM PURCHASE" );
            $sale->albumName($album) if ( $album ne "" );
            $sale->formatType($format);
            $sale->serviceProductID($service_product);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->artistName($artist);
            $sale->labelName($label);
            $sale->price( sprintf( "%.8f", ( $price / $units ) ) );
            $sale->units($units);
            $sale->currencyCode($currency_code);
            $sale->countryCode($country);
            $sale->lineNum($linenum);

            #$args{dumper}($sale); ## for cmd-line testing
            $self->_insertSale( sale => $sale );
        }

        #else { print STDERR "skip: ". join(',', @$line) . "\n"; }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

sub _get_dates {
    my $passed_date = shift;
    my ( $year, $month, $day );
    if ( $passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/ ) {
        $year  = $3;
        $month = $1;
    } elsif ( $passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/ ) {
        $year  = $1;
        $month = $2;
    }
    return undef unless ( $year ne "" && $month ne "" );
    return ( sprintf( "%04d-%02d-01", $year, $month ), sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) ) );
}

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