package RPS::Sale::Match::Koch;

use strict;
use warnings;

use base 'RPS::Sale::Match';

sub new
{
    my ($self, $parent) = @_;
    return undef unless (ref($parent) eq 'HASH');

    return bless $parent;
}

sub FindBestMatch {
	my $self = shift;
    my %in = @_;

    my $result = $self->SUPER::FindBestMatch(@_);

    if ($in{skip_rec} && (!$result || $result->NumProducts != 1))
    {
        if (my $product_id = $self->_clean_match($in{data}))
        {
            RPS::Sale::Match::DEBUG && print STDERR "koch-match $in{data}->{track} $in{data}->{isrc} to $product_id\n";

            $result = new RPS::Sale::Match::Result(
                products => [$product_id],
                num_products => 1,
                import_status => RPS::Sale::Match::STATUS_MATCH,
                map_id => undef,
                rec_products => undef,
                search_products => [],
                detail => $result ? $result->Detail : undef,
            );
        }
    }

	if (defined $result) {
		return $result;
	}
	else {
		$self->{errstr} = "Could not return results!";
		return undef;
	}
}

sub _clean_match
{
    my ($self, $record) = @_;
    return unless ($record->{artist} && length $record->{album} && length $record->{track});

    my $sql = qq|
SELECT product_id
FROM product_catalog_extract
WHERE artist_clean=? and album_clean=? and track_clean=?
|;
    my $sth = $self->dbh()->prepare($sql);
    $sth->execute(
        Common::Util::clean_catalog($record->{artist}),
        Common::Util::clean_catalog($record->{album}),
        Common::Util::clean_catalog($record->{track})
    );

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

1;

