#!/usr/bin/perl

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

use Sale::Match;
use Getopt::Std;

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

my $client_id = $opt{c};
my $table = $opt{t} || 'product_pattern_match';

my $product_id = $opt{p};
my $do_insert  = $opt{i};

unless ( $table eq 'product_pattern_match_new' || $table eq 'product_pattern_match' ) {
    die usage("table $table is not valid!");
}

unless ( $client_id =~ /^\d+$/ && $client_id > 0 ) {
    die usage("client_id '$client_id' must be a number greater than zero");
}

if ( $product_id && $product_id !~ /^\d+$/ ) {
    die usage("if specified, product_id '$product_id' must be a number greater than zero");
}

sub usage {
    my $errstr = shift;
    my $text = ($errstr) ? "ERROR: $errstr\n" : '';
    $text .= "Usage: $0 -c <client_id> [-t <table_name>]\n";
    return $text;
}

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

my $sql_select = <<"ENDOFSQL";
SELECT 
  product_id, product_type, 
  UPPER(upc) as upc, UPPER(isrc) as isrc, 
  artist_norm, album_norm, track_norm,
  artist_scrub, album_scrub, track_scrub, 
  artist_norm_mphon, album_norm_mphon, track_norm_mphon,
  artist_scrub_mphon, album_scrub_mphon, track_scrub_mphon
FROM
  product_catalog_extract
ENDOFSQL

if ($product_id) {
    $sql_select .= " WHERE product_id >= $product_id";
}

# WHERE
#   product_type = 'T'
# and isrc = ''
# and catno != ''
# LIMIT 1

my $sth_select = $match->dbh->prepare($sql_select);
$sth_select->execute();

my $sql_insert = <<"ENDOFSQL";
INSERT INTO $table
  (product_id, product_type, match_md5, pattern, date_created) 
VALUES 
  (?, ?, ?, ?, now())
ENDOFSQL

my $sth_insert = $match->dbh->prepare($sql_insert);

#$match->dbh->do("truncate table $table");

while ( my $data_href = $sth_select->fetchrow_hashref() ) {

    my $match_patterns_href = $match->GetMatchPatterns(
        data      => $data_href,
        min_level => 0
    ) || die $match->errstr;

    while ( my ( $match_md5, $pattern ) = each %{$match_patterns_href} ) {

        my @data = ( $data_href->{product_id}, $data_href->{product_type}, $match_md5, $pattern );

        if ($do_insert) {
            $sth_insert->execute(@data) || die $sth_insert->errstr;
        } else {
            print join( "\t", @data, '\N' ), "\n";
        }

    }
}

$sth_select->finish();
$sth_insert->finish();
$match->dbh->disconnect();

