package RPS::Import::TraxSource2;

use strict;

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 Common::Log;

use lib '/app/tools/data_classes/lib';
use Client::Service;

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

use constant kBitrate192 => '192';
use constant kBitrate320 => '320';
use constant kWavFormat  => 'wav';
use constant kMp3Format  => 'mp3';
use constant kAIFFFormat => 'aiff';

my %fieldMap = (
    5 => {
        label          => 0,
        date           => 1,
        upc            => 2,
        catalog        => 3,
        release_artist => 4,
        release_title  => 5,
        isrc           => 6,
        track_num      => 7,
        track_artist   => 8,
        track_title    => 9,
        track_version  => 10,
        country        => 12,
        bitrate        => 13,
        units          => 19,
        price          => 20,
    },
);

#public methods

sub _importLines {
    my $self        = shift;
    my %args        = @_;
    my $fileObj     = $args{file};
    my $version     = $args{file}->VersionNum();
    my $fileName    = $args{file}->OrigFileName();
    my $serviceID   = Client::Service::DSP_TRAXSOURCE;
    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 $header       = 1;

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

            foreach my $line (@$sheet) {
                ## skip header
                if ( $header && $line->[0] ne 'Label' && $line->[1] ne 'Period' ) {
                    $linenum++;
                    next;
                }
                $header = 0;
                ## skip column titles
                if ( $line->[0] eq 'Label' && $line->[1] eq 'Period' ) {
                    $linenum++;
                    next;
                }

                ## remove any spaces in the country
                my $country;
                $country =~ s/\s+//g;

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

                    if ( $country eq "" ) {
                        $country = "US";
                    }
                } else {
                    $country = "US";
                }

                my $label      = $line->[ $offsets->{label} ];
                my $dateBegin  = $line->[ $offsets->{date} ];
                my $dateEnd    = $line->[ $offsets->{date} ];
                my $upc        = $line->[ $offsets->{upc} ];
                my $catalog    = $line->[ $offsets->{catalog} ];
                my $isrc       = $line->[ $offsets->{isrc} ];
                my $currency   = "USD";
                my $trackTitle = $line->[ $offsets->{track_title} ];
                my $album      = $line->[ $offsets->{release_title} ];
                my $trackNum   = $line->[ $offsets->{track_num} ];
                my $format     = $line->[ $offsets->{bitrate} ];
                my $units      = $line->[ $offsets->{units} ];
                my $price      = $line->[ $offsets->{price} ];
                $price /= $units if ( $units != 0 );

                my $product;
                my $artist;
                ## if there's an ISRC or track number, it's a track, otherwise an album
                if ($isrc) {
                    $product = RPS::File::Sale::TYPE_TRACK;
                    $artist  = $line->[ $offsets->{track_artist} ];
                } elsif ( $trackNum != 0 ) {
                    $product = RPS::File::Sale::TYPE_TRACK;
                    $artist  = $line->[ $offsets->{track_artist} ];
                } else {
                    $product = RPS::File::Sale::TYPE_ALBUM;
                    $artist  = $line->[ $offsets->{release_artist} ];
                }

                if ( $trackNum && !$trackTitle && !$isrc ) {
                    print STDERR "Line $linenum: Track sale without track title or isrc\n";
                    $self->errstr("Line $linenum: Track sale without track title or isrc");
                    return undef;
                }

                ## if we have all components for a valid import, insert into table
                if ( $units && $price && ( ( $trackTitle && $trackTitle ne "Track Title" ) || ( $isrc && $isrc ne "ISRC" ) ) ) {

                    ## higher quality audio is a premium download
                    if (   $format eq kBitrate320
                        || lc($format) eq kWavFormat
                        || lc($format) eq kAIFFFormat ) {
                        $format = RPS::File::Sale::FORMAT_DOWNLOADPREMIUM;
                    } elsif ( $format eq kBitrate192 || lc($format) eq kMp3Format ) {
                        $format = RPS::File::Sale::FORMAT_DOWNLOAD;
                    } else {
                        print STDERR "Line $linenum: Track sale without bitrate\n";
                        $self->errstr("Line $linenum: Track sale without bitrate");
                        return undef;
                    }

                    ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => $line->[ $offsets->{date} ], type => "text" )
                      if ( defined $offsets->{date} );

                    unless ( defined $dateBegin && defined $dateEnd ) {
                        print STDERR "Couldn't get dates from: " . $fileName . "\n";
                        $self->errstr( "couldn't get dates from: " . $fileName );
                        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->upc($upc);
                    $sale->isrc($isrc);
                    $sale->serviceID($serviceID);
                    $sale->serviceProductID($catalog);
                    $sale->artistName($artist);
                    $sale->trackName($trackTitle) if ( $trackNum != 0 );
                    $sale->trackNum($trackNum)    if ( $trackNum != 0 );
                    $sale->albumName($album);
                    $sale->labelName($label);
                    $sale->formatType($format);
                    $sale->units($units);
                    $sale->price($price);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $sale->lineNum($linenum);

                    $self->_insertSale( sale => $sale );
                }
                $linenum++;
            }
        }
        $sheet_count++;
    }
    return $linenum;
}

#
# Private methods
#

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