#------------------------------------------------------------
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package BookPub::DB::Item::SalePriceExceptionRule;
use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Assert;
use base 'Common::DB::Item';

use constant kTable => 'sale_price_exception_rule';
use constant kDB    => Common::DB::Item::kClientDB;

use constant kMatchKeys => 'service_id version currency_code price_type_id
                            price_type_qualifier_id product_id country_code list_price';

sub FindRule {
    my $class = shift;
    my %args  = @_;

    my $sql = "SELECT * FROM " . kTable . " WHERE ";
    $sql .= $class->_matchCriteria(%args);

    my $collection = $class->SUPER::GetAll($sql);
    Common::Log::Debug("QUERY: $sql");

    return $collection->next();
}

sub Delete {
    my $class = shift;
    my %args  = @_;

    my $sql = "DELETE FROM " . kTable . " WHERE ";
    $sql .= $class->_matchCriteria(%args);

    my $dbo = Common::RSApp::GetClientDB();
    Common::Log::Debug("QUERY: $sql");
    $dbo->DoCmd($sql);
}

sub _matchCriteria {
    my $class = shift;
    my %args  = @_;
    my @criteria;

    my @fields = split( /\s+/, kMatchKeys );

    foreach my $key (@fields) {

        # We need to do things a little differently for the price_type_qualifier_id,
        # since multiple values (NULL, 0, and 5) of it will be treated the same.
        if ( $key eq 'price_type_qualifier_id' ) {
            if ( defined $args{$key} && $args{$key} != 0 && $args{$key} != 5 ) {
                push @criteria, "price_type_qualifier_id = " . $class->quote( $args{$key} );
            } else {
                push @criteria, "(price_type_qualifier_id IN (0,5) OR price_type_qualifier_id IS NULL)";
            }
        } else {
            if ( defined( $args{$key} ) && length( $args{$key} ) ) {
                push( @criteria, "$key = " . $class->quote( $args{$key} ) );
            } else {
                push( @criteria, "$key IS NULL" );
            }
        }
    }

    return join( " AND ", @criteria );
}

1;
