#------------------------------------------------------------
# Copyright (C) 2008 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package Job::DB::Item::JobRunRule;

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

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

use constant kTable => 'job_run_rule';
use constant kDB    => Common::DB::Item::kCommonDB();

sub GetAllForHostname {
    my ( $class, $hostname ) = @_;

    # !!! As an experiment, we'll overload the rules to allow 'host_class' to appear in hostname
    #
    my $sql =
        "SELECT * FROM "
      . kTable
      . " WHERE (hostname='$hostname' OR hostname IN (select class from job_host_class where hostname='$hostname'))";

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

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

    my $dbo = Common::RSApp::GetCommonDB();

    my $sql = 'SELECT distinct hostname FROM ' . kTable;
    my $sth = $dbo->DoCmd($sql);

    my @hosts;

    while ( my $hr = $sth->fetchrow_hashref() ) {
        push @hosts, $hr->{hostname};
    }

    return @hosts;
}

sub getCacheDate {
    my $class = shift;
    my $date  = shift;
    my $dbo   = Common::RSApp::GetCommonDB;

    my $sql = "SHOW TABLE STATUS WHERE Name =  " . $class->quote(kTable);
    $sql .= " AND Update_time > " . $class->quote($date) if ($date);

    #Common::Log::Debug( "QUERY: $sql" );

    my $sth = $dbo->DoCmd($sql) || return;
    my $result = $sth->fetchrow_hashref();

    return $result->{Update_time};
}

sub getTableMd5 {
    my $self = shift;

    my $dbo = Common::RSApp::GetCommonDB;
    my $sql = "CHECKSUM TABLE " . kTable;
    my $sth = $dbo->DoCmd($sql) || return 0;
    my $result = $sth->fetchrow_hashref();

    return $result->{Checksum};
}

1;
