package RPS::Sale::Match::EMI;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';
use lib '/app/tools/data_classes/lib';
use Client::Service;
use Common::Log;
use RPS::DB::Item::Product;

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


sub _cleanClientProductID
{
    my ($self, $data) = @_;

    my $dti= $data->{client_product_id};

    # Default is a noop
    return $dti;
}


sub _get_track_matches
{
    my ($self, $data, $skipRec) = @_;

    # First, let's create clean or 'normalized' versions of the parameters
    # we might use to construct the query.
    #
    my $trackClean = $self->_cleanTrack($data);
    my $clientProductID = $self->_cleanClientProductID($data);

#    Common::Log::Print("clientProductID: $clientProductID   trackClean: $trackClean", $data);

    if ($clientProductID && $trackClean)
    {
        my $dbo = Common::RSApp::GetClientDB();


        my $sql = "SELECT product.product_id AS track_product_id"
         . ",track.title AS track_title"
         . ",track.title_clean AS track_title_clean"
         . ",track.custom_1 AS track_custom_1"
         . " FROM product LEFT JOIN track ON (product.asset_id = track.track_id)"
         . " WHERE product.product_type_id=" . RPS::DB::Item::Product::kProductTypeDigitalTrack
         . " AND track.custom_1=".$dbo->DBQuote($clientProductID);


        my $sth = $dbo->DoCmd($sql);


        # !!!
        # The biggest problem I see with this approach is for recommended searches.
        # This method will end up possibly skipping items where the track title is way off,
        # but the DTI does match.
        #
        # I think in that case, I will need to add this product to what the inherited method returns.

        # !!! There should ONLY BE ONE of these.
        #
        if (1 == $sth->rows())
        {
            my $hr = $sth->fetchrow_hashref();

            
            # We don't need to test the DTI, since it was specified in the WHERE clause of the query.
            # Just see if the title is close enough.
            #
            my $titleMatchFlag = $self->_testTrackTitle(row => $hr, data => $data, clean => $trackClean, threshold => 0.70);

            # JPK - For the trial, we now want to just go ahead and match when the DTI matches, even if the title is off.
            # At some point it would be nice to note this someplace.  Right now, we don't have anyplace to put it...
            #
            if (1)
#            if (RPS::Sale::Match::ISMATCH == $titleMatchFlag)
            {
                my %matches;
                $matches{$hr->{track_product_id}} = 
                {
                    data => $hr,  
                    status => RPS::Sale::Match::MATCH,
                    weight => 5,
                };

                return \%matches;
            }
            elsif (! $skipRec)
            {
                # Since the DTI does match, this should probably be a suggested match.
                #
                my $matchesRef = $self->SUPER::_get_track_matches($data, $skipRec);
                if (! defined $matchesRef->{$hr->{track_product_id}})
                {
                    $matchesRef->{$hr->{track_product_id}} = 
                    {
                        data => $hr,  
                        status => RPS::Sale::Match::SUGGEST,
                        weight => 1,
                    };
                }

                return $matchesRef;
            }

        }
    }

    return $self->SUPER::_get_track_matches($data, $skipRec);
}


sub _testUPC
{
    my ($self, %args) = @_;

    my $row = $args{row};
    my $data = $args{data};


    # JPK - We've not been doing a great job with EAN ids where the service has removed the _two_ leading zeroes.
    # The inherited logic probably needs to be rewritten, but in the meanwhile I'll override this method
    # to do a simplistic test:   If the value has fewer than 13 characters, I'll pad with zeroes up to 13 and
    # then try to match it to the two upc/ean fields.  If that fails I'll call the inherited method to do it's stuff.
    #

    my $upc = $data->{upc};
    if ($upc)
    {
        my $pad = 13 - (length $upc);
        if ($pad)
        {
            my $padString = '0' x $pad;
            $upc = $padString . $upc;
        }

        my $metaUPC = $row->{upc};
        my $metaUPCAlt = $row->{upc_alt};

        if ((defined $metaUPC && $upc eq $metaUPC) || (defined $metaUPCAlt && $upc eq $metaUPCAlt))
        {
            return (RPS::Sale::Match::ISMATCH, 1);
        }
    }

    return $self->SUPER::_testUPC(%args);
}


# Overriding this to call any match with an exact UPC a 'real' match...
# Not that I think this is a good idea, but that's what EMI seems to want.
#
sub _scoreAlbumRow
{
    my ($self, %args) = @_;
    my $hr = $args{row};
    my $data = $args{data};

    my ($upcFlag, $upcExactFlag) = $self->_testUPC(row => $hr, data => $data);

    if (RPS::Sale::Match::ISMATCH == $upcFlag && $upcExactFlag)
    {
        # !!! This is quite the hack...
        # !!! A weight of '5' should easily win over any other matches.
        #
        return (RPS::Sale::Match::MATCH, 5);
    }
    return $self->SUPER::_scoreAlbumRow(%args);
}


    
1;

