
#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2011 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------
package BookPub::DB::Item::BestSellerBookProduct;

use strict;
use warnings;
use Data::Dumper;

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';
use Common::Assert;

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

use base 'Common::DB::Item';

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

    assert( $args{list_id}, "List ID Required" );

    my $listID = $args{list_id};

    my $sql = "UPDATE " . kTable . " SET status = 'old' WHERE best_seller_list_id = $listID AND status = 'current'";

    if ( $args{excluded_ids} ) {
        my @quotedIDs;
        foreach my $id ( @{ $args{excluded_ids} } ) {
            push @quotedIDs, $class->quote($id);
        }
        my $rowIDString = join( ',', @quotedIDs );

        if ($rowIDString) {
            $sql .= " AND best_seller_book_product_id NOT IN ( $rowIDString )";
        }
    }

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

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

    assert( %args,             "No args passed" );
    assert( $args{product_id}, "Product ID Required" );

    # product_id can be either a single id, or a reference to an array of ids.
    # We'll convert the single ID to an array of one
    #
    my @quotedProductIDs;
    if ( 'ARRAY' ne ref( $args{product_id} ) ) {
        push @quotedProductIDs, $class->quote( $args{product_id} );
    } else {
        foreach my $id ( @{ $args{product_id} } ) {
            push @quotedProductIDs, $class->quote($id);
        }
    }
    my $productIDString = join( ',', @quotedProductIDs );

    my $sql = "SELECT * FROM " . kTable . " WHERE product_id IN ( $productIDString ) AND status='current'";
    return $class->GetAll($sql);
}

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

    assert( $args{id}, "ID Required" );

    my $id = $args{id};

    my $sql = "UPDATE " . kTable . " SET last_verified = NOW() WHERE best_seller_book_product_id = $id";

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

1;
