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

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

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

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

sub GetAllSortedByName {
    my ($class) = @_;

    my $sql = "SELECT * FROM " . kTable . " ORDER BY name";
    return $class->GetAll($sql);
}

sub GetAllSimpleSortedByName {
    my ($class) = @_;

    my $sql = "SELECT * FROM " . kTable . " WHERE dynamic = 0 ORDER BY name";
    return $class->GetAll($sql);
}

sub GetFirstWithAccess {
    my ( $class, $userID ) = @_;

    my $sql = "SELECT * FROM " . kTable . " WHERE public = 1 OR created_by = $userID ORDER BY name LIMIT 1";
    return $class->GetAll($sql);
}

sub LookupByGlobalID {
    my ( $class, $global_id ) = @_;

    assert($global_id);

    my $sql = "SELECT * FROM " . kTable . " WHERE global_id = " . $class->quote($global_id);
    Log->debug("QUERY: $sql");
    return $class->GetAll($sql)->next;
}

# Delete all global watch lists that are not in the list of IDs passed
sub DeleteByGlobalID {
    my $class     = shift;
    my %args      = @_;
    my $globalIDs = $args{global_id};
    my $dbo       = Common::RSApp::GetClientDB();
    my @ids;

    assert($globalIDs);
    assert( ref($globalIDs) );

    foreach my $id (@$globalIDs) {
        push( @ids, $class->quote($id) );
    }

    my $sql = "DELETE FROM " . kTable . " WHERE global_id IS NOT NULL AND " . "global_id NOT IN ( " . join( ', ', @ids ) . ")";

    Log->debug("QUERY: $sql");

    return $dbo->DoCmd($sql);
}

1;
