package Sale::Match::CMG;

use strict;

use base '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->_cmg_match( \@{ $result->ProductIDs() }, $in{data} ) ) {
            Sale::Match::DEBUG && print STDERR "cmg-match $in{data}->{artist} $in{data}->{track} $in{data}->{isrc} to $product_id\n";

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

    return $result if ( defined $result );

    $self->{errstr} = "Could not return results!";
    return undef;
}

sub _cmg_match {
    my ( $self, $products, $record ) = @_;
    return unless ( $record->{artist} && $record->{track} && $record->{isrc} );

    my $product_id_list = join( ',', @$products );
    my $sql = qq|
SELECT
    product_id, ifnull(release_date, '2199-12-31') as release_date,
    artist.name as artist_name, artist.name_clean as artist_clean,
    album.title as album_title, album.title_clean as album_clean,
    track.title as track_title, track.title_clean as track_clean,
    isrc
FROM
    product inner join track on (asset_id=track_id)
    inner join artist on(track.artist_id=artist.artist_id)
    inner join album on (track.album_id=album.album_id) 
    inner join master on(track.master_id=master.master_id)
WHERE product_id in($product_id_list)
ORDER BY release_date
|;
    my $sth = $self->dbh()->prepare($sql);
    $sth->execute();
    return undef unless ( $sth->rows() >= 1 );

    my $product_id = 0;
    my ( $albumClean, $albumCleanAlt );
    $albumClean = $albumCleanAlt = $record->{album};
    $albumCleanAlt =~ s/^$record->{artist}\W+//;
    $albumCleanAlt = Common::Util::clean($albumCleanAlt);
    $albumClean    = Common::Util::clean($albumClean);

    my $artistClean = Common::Util::clean( $record->{artist} );
    my $trackClean  = Common::Util::clean( $record->{track} );

    while ( my $row = $sth->fetchrow_hashref() ) {
        next unless ( $row->{artist_clean} eq $artistClean
            || Common::Util::word_containment( $row->{artist_name}, $record->{artist} ) );
        next unless ( $row->{track_clean} eq $trackClean && lc $row->{isrc} eq lc $record->{isrc} );

        if ( $record->{album} ) {
            my $row_albumClean = Common::Util::clean( $row->{album_name} );
            if (   $row->{album_clean} eq $albumClean
                || $row->{album_clean} eq $albumCleanAlt
                || Common::Util::word_containment( $row->{album_title}, $record->{album} ) ) {
                $product_id = $row->{product_id};
                $sth->finish();
                last;
            }
        } else {
            $product_id = $row->{product_id};
            $sth->finish();
            last;
        }
    }

    return $product_id || undef;
}

1;

