#!/usr/bin/perl

use strict;

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

use RPS::Sale::Match;
use RPS::File::Sale;
use RPS::File::File;
use Common::Util qw(clean norm scrub mphon);
use Common::RSDB;
use Getopt::Std;

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

my $client_id = $opt{c} || die "No client_id!\n";
my $sale_id   = $opt{s} || die "No sale_id!\n";
my $product_id = $opt{p};

unless ( $client_id =~ /^\d+$/ && $client_id > 0 && $sale_id =~ /^\d+$/ && $sale_id > 0 ) {
    die "ERROR: You must specify a valid client_id and sale_id\n\nUsage: $0 -c <client_id> -s <sale_id>\n";
}

my $dbo = new Common::RSDB( client_id => $client_id, dbi_attr => { RaiseError => 1 } );

my $dbh = $dbo->DBH();

my $match = RPS::Sale::Match->new( client_id => $client_id );

my $sale = RPS::File::Sale->new( sale_id => $sale_id, dbo => $dbo );

my $file = RPS::File::File->new( file_id => $sale->FileID );

# required data elements for tracks (albums don't require isrc and track)
my $data = {
    product_type       => $sale->ProductType,
    upc                => $sale->UPC,
    isrc               => $sale->ISRC,
    artist             => $sale->ArtistName,
    album              => $sale->AlbumName,
    track              => $sale->TrackName,
    track_num          => $sale->TrackNum,
    service_id         => $file->ServiceID,
    service_product_id => $sale->ServiceProductID
};

print_header(
    'S/ID',     # import_status for input line / product_id for product line(s)
    'M/L',      # number of matches for input line / confidence level for product line(s)
    'MTYPE',    # match_type
    'PATTERN',
    'PT',       # product_type
    'UPC',
    'ISRC',
    'ARTIST',
    'ALBUM',
    'TRACK'
);

# returns result object
my $result = $match->FindBestMatch(
    data            => $data,
    min_match_level => 90,
    min_rec_level   => 70,

    # skip_rec => 1
) || die $match->errstr;

my $product_data = product_data( @{ $result->ProductIDs }, @{ $result->RecProductIDs } ),

  print_row(
    $result->ImportStatus,    $result->NumProducts, '-',         '-',
    $sale->ProductType,       $sale->UPC,           $sale->ISRC, norm( $sale->ArtistName ),
    norm( $sale->AlbumName ), norm( $sale->TrackName )
  );

foreach my $product_id ( @{ $result->ProductIDs }, @{ $result->RecProductIDs } ) {
    print_row(
        $product_id,                     $result->Level($product_id),
        $result->MatchType($product_id), $result->Pattern($product_id),
        @{ $product_data->{$product_id} }
      ),
      "\n";
}
print "\n";

if ($product_id) {
    my $map_id = $match->MakeMatch(
        data       => $data,
        product_id => $product_id
    );

    if ($map_id) {
        print "Input data mapped to product_id = $product_id, map_id = $map_id\n";
    } else {
        print "ERROR: could not map input data to product_id = $product_id: " . $match->errstr;
    }
}

sub print_row {
    printf "%4s  %4s  %5s  %6s  %2s  %-15s  %-15s  %-25s  %-25s  %-40s\n", @_;
}

sub print_header {
    print_row(@_);
    print_row( '-' x 4, '-' x 4, '-' x 5, '-' x 6, '-' x 2, '-' x 15, '-' x 15, '-' x 25, '-' x 25, '-' x 40 );
}

sub product_data {
    my @product_ids = @_;

    return undef unless scalar @product_ids;

    my $product_ids_joined = join( ',', @product_ids );
    my $sql =
qq{select product_id, product_type, upc, isrc, artist_norm, album_norm, track_norm from product_catalog_extract where product_id in ($product_ids_joined)};

    my %data;
    my $sth = $dbh->prepare($sql);
    $sth->execute();
    while ( my (@row) = $sth->fetchrow_array() ) {
        my $product_id = shift @row;
        $data{$product_id} = \@row;
    }
    return \%data;
    $sth->finish();

}
$dbh->disconnect();

