#!/usr/bin/perl

use strict;

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

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

my %opt;
getopts( 'c:t:k:p:b:l:', \%opt );

my $client_id    = $opt{c} || die "No -c <client_id>!\n";
my $product_type = $opt{p} || die "No -p <product_type>!\n";
my $search_type  = $opt{t} || die "No -t <search_type>!\n";
my $keywords     = $opt{k} || die "No -k <keywords>!\n";
my $bool_terms   = $opt{b} || 'OR';
my $limit        = $opt{l} || 10;

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

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

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

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

# returns result object
my $result = $match->SearchCatalog(
    type     => $search_type,
    keywords => $keywords,
    data     => {
        artist => 'Eyedea & Abilities',
    },
    product_type => $product_type,
    bool_terms   => $bool_terms,
    bool_fields  => 'OR',
    limit        => $limit
) || die $match->errstr . " (keywords = $keywords)";

print 'RESULTS: ' . join( ", ", ( @{ $result->SearchProductIDs } ) ) . "\n";

my $product_data = product_data( @{ $result->SearchProductIDs } );

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

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

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

sub product_data {
    my @product_ids = @_;

    return undef unless scalar @product_ids > 0;

    print "Why am I here?\n";
    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 $sql =
qq{select product_id, product_type, upc, isrc, artist_name, album_name, track_name 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();

