#!/usr/bin/perl
use strict;

# -----------------------------------------
# input params: all required
#
# 	-c <client_id>
# 	-f <file_id>
#
# -----------------------------------------
# what it does:
#
#   - for every napster file with open status
# 	  - get unmatched sale records from db
#     - use (artist/norm|album/norm) along with upc isrc track/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::Sale;
use RPS::File::File;

use constant SERVICE_ID => 10;

use Getopt::Std;

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

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

my %opt;
getopts( 'c:f:', \%opt );

usage() unless ( $opt{c} && $opt{f} );

my $cnt_map = 0;
my $summary = map_unmatched( $opt{c}, $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 matched\n";

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

sub map_unmatched {
    my $client_id      = shift;
    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;
        print "checking $file_id\n";
        $summary{$file_id} = 0;

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

        while ( my $sale = $sales->GetNext() ) {
            my $isrc = $sale->ISRC;

            next unless ($isrc);
            my $product_id;

            if ($isrc)    # exclude album
            {
                my $sql = 'select product_id from product_catalog_extract where isrc=? and product_type="T"';

                my $sth = $dbo->DBH->prepare($sql);
                $sth->execute($isrc);

                $product_id = $sth->fetchrow_arrayref()->[0] if ( $sth->rows == 1 );
            }

            next unless $product_id;
            print "match $product_id with $isrc\n";

            $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 [-c CLIENT_ID -f FILE_ID]\n";
    exit();
}
