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

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

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

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

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

sub GetAllSorted {
    my $class     = shift;
    my %args      = @_;
    my $orderBy   = $args{orderBy};
    my $desending = $args{desending};
    my $resolved  = $args{resolved};
    my $current   = $args{current};
    my $serviceID = $args{service_id};
    my $productID = $args{product_id};
    my $type      = $args{type};
    my @where;

    push( @where, "service_id = " . $class->quote($serviceID) ) if ($serviceID);

    push( @where, "date_resolved IS NOT NULL AND date_resolved <> 0" ) if ( !$current && $resolved );
    push( @where, "( date_resolved IS NULL OR date_resolved = 0 )" )   if ( $current  && !$resolved );
    push( @where, kTable . ".type = " . $class->quote($type) )         if ($type);
    push( @where, "product_monitor_item.product_id=" . $class->quote($productID) ) if ($productID);

    # !!! Excluding Borders
    push( @where, "service_id != 49" );

    my $sql = "SELECT " . kTable . ".* FROM " . kTable . " INNER JOIN product_monitor_item USING (product_monitor_item_id) ";

    $sql .= " WHERE " . join( ' AND ', @where ) if (@where);

    $sql .= " ORDER BY $orderBy " if ($orderBy);
    $sql .= " DESC " if ( $desending && $orderBy );

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

    return $class->SUPER::GetAll($sql);
}

sub GetCount {
    my $class     = shift;
    my %args      = @_;
    my $resolved  = $args{resolved};
    my $current   = $args{current};
    my $serviceID = $args{service_id};
    my $productID = $args{product_id};
    my $type      = $args{type};
    my @where;

    assert($type);

    push( @where, "service_id = " . $class->quote($serviceID) ) if ($serviceID);

    push( @where, "date_resolved IS NOT NULL AND date_resolved <> 0" ) if ( !$current && $resolved );
    push( @where, "( date_resolved IS NULL OR date_resolved = 0 )" )   if ( $current  && !$resolved );
    push( @where, kTable . ".type = " . $class->quote($type) )         if ($type);
    push( @where, "product_id=" . $class->quote($productID) )          if ($productID);

    # !!! Excluding Borders
    push( @where, "service_id != 49" );

    my $sql = "SELECT COUNT(*) as count FROM " . kTable . " INNER JOIN product_monitor_item USING (product_monitor_item_id) ";

    $sql .= " WHERE " . join( ' AND ', @where ) if (@where);

    Log->debug("QUERY: $sql");
    my $collection = $class->SUPER::GetAll($sql);
    my $dbItem = $collection->next() || return 0;

    return $dbItem->{count};
}

sub CountActiveAlertsForProductIDs {
    my ( $class, $productIDArray ) = @_;
    assert( $productIDArray,                 'missing product id array argument' );
    assert( 'ARRAY' eq ref($productIDArray), 'product id argument must be an array reference' );

    my $productIDString = join( ',', @$productIDArray );

    my $sql =
        "SELECT COUNT(*) FROM "
      . kTable
      . " LEFT JOIN product_monitor_item USING ( product_monitor_item_id )"
      . " WHERE product_monitor_item.product_id IN ($productIDString)"
      . " AND product_monitor_alert.date_resolved IS NULL";

    # !!! Excluding Borders
    $sql .= " AND service_id != 49";

    my $dbo = Common::RSApp::GetClientDB();
    my $sth = $dbo->DoCmd($sql);
    my $hr  = $sth->fetchrow_hashref();
    return $hr->{'COUNT(*)'};
}

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

    my $sql =
        "SELECT COUNT(*) FROM "
      . kTable
      . " LEFT JOIN product_monitor_item USING ( product_monitor_item_id )"
      . " WHERE product_monitor_alert.date_resolved IS NULL";

    # !!! Excluding Borders
    $sql .= " AND service_id != 49";

    my $dbo = Common::RSApp::GetClientDB();
    my $sth = $dbo->DoCmd($sql);
    my $hr  = $sth->fetchrow_hashref();
    return $hr->{'COUNT(*)'};
}

sub GetDistinctServiceIDs {
    my $class = shift;

    my $sql = "SELECT DISTINCT(service_id) FROM " . kTable . " INNER JOIN product_monitor_item USING (product_monitor_item_id)";

    # !!! Excluding Borders
    $sql .= " WHERE service_id != 49";

    return $class->SUPER::GetAll($sql);
}

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

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

    my $sql =
        "SELECT * FROM "
      . $class->_table()
      . " INNER JOIN product_monitor_alert USING (product_monitor_alert_id) "
      . " INNER JOIN product_monitor_item USING (product_monitor_item_id) "
      . "WHERE "
      . " product_id = "
      . $class->quote( $args{product_id} ) . " AND "
      . " service_id = "
      . $class->quote( $args{service_id} ) . " AND "
      . " status = 'current'";

    my $collection = $class->SUPER::GetAll($sql);
    return $collection->next();
}

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

    assert( %args, "No args passed" );
    assert( $args{product_id} || $args{book_id}, "Product or Book ID Required" );
    assert( $args{service_id}, "Service ID Required" );

    my $sql =
        "UPDATE "
      . $class->_table()
      . " INNER JOIN product_monitor_alert USING (product_monitor_alert_id) "
      . " INNER JOIN product_monitor_item USING (product_monitor_item_id) "
      . " INNER JOIN book_product USING (product_id) "
      . "SET date_resolved = NOW() "
      . "WHERE "
      . " service_id = "
      . $class->quote( $args{service_id} )
      . " AND date_resolved IS NULL ";

    if ( $args{exclude_product_id} ) {
        $sql .= " AND product_id <> " . $class->quote( $args{exclude_product_id} );
    }

    if ( $args{book_id} ) {
        $sql .= " AND book_id = " . $class->quote( $args{book_id} );
    } else {
        $sql .= " AND product_id = " . $class->quote( $args{product_id} );
    }

    if ( $args{type} ) {
        $sql .= " AND " . kTable . ".type = " . $class->quote( $args{type} );
    }

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

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

    assert( %args, "No args passed" );
    assert( $args{product_id} || $args{book_id}, "Product or Book ID Required" );
    assert( $args{service_id}, "Service ID Required" );

    my $sql =
        "UPDATE "
      . kTable
      . " INNER JOIN product_monitor_item USING (product_monitor_item_id) "
      . "SET date_resolved = NOW() "
      . "WHERE "
      . " service_id = "
      . $class->quote( $args{service_id} )
      . " AND product_id = "
      . $class->quote( $args{product_id} )
      . " AND status = 'old' "
      . " AND date_resolved IS NULL ";

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

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

    my $bookID         = $args{book_id};
    my $excludeProduct = $args{exclude_product_id};
    my $productID      = $args{product_id};
    my $serviceID      = $args{service_id};

    assert($serviceID);
    assert( $productID || $bookID );

    my $sql =
        "UPDATE "
      . kTable
      . " INNER JOIN product_monitor_item USING (product_monitor_item_id) "
      . " INNER JOIN book_product USING (product_id) "
      . "SET date_resolved = NOW() "
      . "WHERE service_id = "
      . $class->quote($serviceID)
      . " AND date_resolved IS NULL ";

    if ($productID)      { $sql .= " AND product_id = " . $class->quote($productID); }
    if ($bookID)         { $sql .= " AND book_id    = " . $class->quote($bookID); }
    if ($excludeProduct) { $sql .= " AND product_id <> " . $class->quote($excludeProduct); }

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

1;
