#!/usr/bin/perl
use strict;

# -----------------------------------------
# input params: all optional
#
# 	-f <file_id>
# 	-c check only - no updates performed
# 	-v verbose
#
# -----------------------------------------
# what it does:
#
#   - for every iTunes file with open status
# 	  - get unmatched sale records from db
#     - get upc from client_product_id along with track clean/norm to match
#
# -----------------------------------------

use lib '/app/tools/common/lib';
use Common::RSDB;
use Common::Util qw(clean norm);

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

use constant CLIENT_ID  => 31;
use constant CLIENT_DIR => 'sanctuary_records_group';
use constant SERVICE_ID => 11;
use constant LOG        => 'automap_iTunes.log';

use Getopt::Std;

# -----------------------------------------

unless ( -t STDIN ) {
    my $log = join( '/', '/app/shared/sale_import', CLIENT_DIR, LOG );
    select STDERR if open( STDERR, ">>$log" );
}

print "running with args '@ARGV'\n";

my %opt;
getopts( 'vcf:', \%opt );

my $UPDATE = $opt{c} ? 0 : 1;
my $DEBUG  = $opt{v} ? 1 : 0;

my $cnt_map = 0;
my $summary = map_unmatched( $opt{f} );

map {
    print "matched $summary->{$_} for file $_\n" if $summary->{$_};
    $cnt_map += $summary->{$_};
} keys %$summary;

print scalar( keys(%$summary) ) . " files analyzed\n";
print "$cnt_map total records mapped\n";

# -----------------------------------------

sub map_unmatched {
    my $file_id_single = shift;
    my %summary        = ();

    my $sql = 'SELECT file_id from file where service_id=' . SERVICE_ID;
    $sql .= ' and file_status=' . File::File::STATUS_OPEN;
    $sql .= ' and remaining_exceptions > 0';
    $sql .= " and file_id=$file_id_single" if $file_id_single;

    my $files = RPS::File::Files->new( client_id => CLIENT_ID );
    return unless $files->getByQuery($sql);

    my $dbo = Common::RSDB->new( client_id => CLIENT_ID );

    while ( my $fileObj = $files->GetNext ) {
        my $file_id = $fileObj->FileID;
        $DEBUG && print "checking $file_id\n";
        $summary{$file_id} = 0;

        my $sales = File::Sales->new( client_id => CLIENT_ID );
        $sales->GetUnmatchedByFile( file_id => $file_id );

        while ( my $sale = $sales->GetNext() ) {
            my $altUPC = $sale->ClientProductID;
            next unless ( $altUPC =~ s/_\w+$// );

            my $trackClean = clean( $sale->TrackName );
            my $trackNorm  = norm( $sale->TrackName );

            my $isrc = $sale->ISRC;

            my $sql =
              'select product_id, isrc from product_catalog_extract where upc=? and (track_clean=? or track_norm=?) and product_type="T"';

            my $sth = $dbo->DBH->prepare($sql);
            $sth->execute( $altUPC, $trackClean, $trackNorm );

            my $product_id;
            if ( $sth->rows == 1 ) {
                $product_id = $sth->fetchrow_arrayref()->[0];
            } elsif ( $sth->rows > 1 && $isrc ) {
                while ( my $row = $sth->fetchrow_arrayref() ) {
                    next unless ( $isrc eq $row->[1] );
                    $product_id = $row->[0];
                    last;
                }
            }
            next unless $product_id;

            $DEBUG && print "match $product_id with $altUPC $trackClean $trackNorm $isrc\n";

            if ($UPDATE) {
                $sale->ImportStatus(File::Sale::STATUS_BATCH_MAPPED);
                $sale->ProductID($product_id);
                $sale->Save();
            }

            $summary{$file_id}++;
        }

        # oh what the heck, go ahead and make sure the metrics are accurate
        $fileObj->UpdateSummary() if $summary{$file_id};

    }
    return \%summary;
}

sub usage {
    my $err = shift;

    print "ERROR: $err\n";
    print "Usage: $0 [-f FILE_ID -c COUNT]\n";
    exit();
}
