package RPS::Import::UniversalCADigital;

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 lib '/app/tools/data_classes/lib';

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

my %fieldMap = (
    5 => {
        date_row   => 0,
        date_col   => 0,
        artist     => 1,
        track      => 2,
        album      => 3,
        product    => 4,
        format     => 6,
        isrc       => 7,
        upc        => 8,
        catalog_id => 9,
        units      => 10,
        price      => 11,
    },
);

my %format_map = (
    'ota permanent downloads'                        => RPS::File::Sale::FORMAT_DOWNLOAD,
    'permanent downloads'                            => RPS::File::Sale::FORMAT_DOWNLOAD,
    'video downloads'                                => RPS::File::Sale::FORMAT_DOWNLOAD,    # was FORMAT_VIDEO (FB1324)
    'true tones'                                     => RPS::File::Sale::FORMAT_RINGTONE,
    'video streams'                                  => RPS::File::Sale::FORMAT_STREAM,      # was FORMAT_VIDEOSTREAM (FB1324)
    'streams'                                        => RPS::File::Sale::FORMAT_STREAM,
    'subscription ota permanent downloads audio'     => RPS::File::Sale::FORMAT_DOWNLOAD,
    'client plays tethered downloads'                => RPS::File::Sale::FORMAT_TETHERED,
    'portable subscription client plays tethered dl' => RPS::File::Sale::FORMAT_TETHERED,
    'portable subscription device plays'             => RPS::File::Sale::FORMAT_DOWNLOAD,
    'portable subscription streams'                  => RPS::File::Sale::FORMAT_STREAM,
);

#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   = $args{file}->ServiceID;
    my $sheet_count = 0;

    return undef unless ( defined $args{sheets} && defined $version );

    my $offsets     = $fieldMap{$version};
    my $sheet_names = $args{sheet_names};
    my $linenum     = 1;
    my ( $dateBegin, $dateEnd );
    foreach my $sheet ( @{ $args{sheets} } ) {
        $linenum = 1;
        if ( $sheet_names->[$sheet_count] !~ /summary/i ) {
            my $lines = $sheet;
            ( $dateBegin, $dateEnd ) = _getDates( $lines->[ $offsets->{date_row} ]->[ $offsets->{date_col} ] ) if ( $sheet_count == 0 );
            foreach my $line (@$sheet) {
                $line->[ $offsets->{format} ] =~ s/(\(|\))//g;
                my $artist     = $line->[ $offsets->{artist} ];
                my $track      = $line->[ $offsets->{track} ];
                my $album      = $line->[ $offsets->{album} ];
                my $format     = $format_map{ lc( $line->[ $offsets->{format} ] ) };
                my $prodtype   = $line->[ $offsets->{product} ];
                my $units      = $line->[ $offsets->{units} ];
                my $price      = $line->[ $offsets->{price} ];
                my $isrc       = $line->[ $offsets->{isrc} ];
                my $upc        = $line->[ $offsets->{upc} ];
                my $catalog_id = $line->[ $offsets->{catalog_id} ];
                my $country    = "CA";
                my $currency   = "CAD";
                $price /= $units if ( $units != 0 );

                my $mediaType = RPS::DB::Item::MediaType::kMediaTypeAudio;

                if ( $line->[ $offsets->{format} ] =~ /^video (downloads|streams)$/i ) {
                    $mediaType = RPS::DB::Item::MediaType::kMediaTypeVideo;
                }

                if ( $artist && $units && ( $track && $track !~ /track title/i || $album && $album !~ /title/i ) && $format ) {

                    unless ( defined $dateBegin && defined $dateEnd ) {
                        print STDERR "Couldn't get dates from: " . $lines->[ $offsets->{date_row} ]->[ $offsets->{date_col} ] . "\n";
                        $self->errstr( "couldn't get dates from: " . $lines->[ $offsets->{date_row} ]->[ $offsets->{date_col} ] );
                        return undef;
                    }
                    unless ( $format ne "" ) {
                        print STDERR "Unknown format: " . $line->[ $offsets->{format} ] . "\n";
                        $self->errstr( "Unknown format: " . $line->[ $offsets->{format} ] );
                    }
                    unless ( $prodtype ne "" ) {
                        print STDERR "Unknown product type: " . $line->[ $offsets->{product} ] . "\n";
                        $self->errstr( "Unknown product type: " . $line->[ $offsets->{product} ] );
                    }

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

                    $sale->mediaType($mediaType);
                    $sale->productType($prodtype);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->artistName($artist);
                    $sale->albumName($album) if ( $album ne "" );
                    $sale->trackName($track) if ( $track ne "" && $prodtype eq RPS::File::Sale::TYPE_TRACK );
                    $sale->isrc( ($isrc) ) if ( $isrc ne "" );
                    $sale->upc(  ($upc) )  if ( $upc ne "" );
                    $sale->serviceProductID($catalog_id) if ( $catalog_id ne "" );
                    $sale->formatType($format);
                    $sale->units($units);
                    $sale->price($price);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $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." a:".$album." f:".$format."\n"; }
                $linenum++;
            }
        }
        $sheet_count++;
    }
    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my $passed_date = shift;
    $passed_date =~ s/ \-.*$//;
    $passed_date =~ m/(\w+) (\d{4})/;
    my $monthName = $1;
    my $year      = $2;
    my $month     = Decode_Month($monthName);
    if ( $month ne "" && $year ne "" ) {
        my $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
        my $dateEnd = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );
        return ( $dateBegin, $dateEnd );
    }
    return undef;
}

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