# -*-perl-*-

# $Id$

# database interface to the limits tables
# (su_limits, su_lim_active, su_lim_alias)

# $Log$
# Revision 1.5  2003/06/09 14:45:11  thomas
# schema version of database
#
# Revision 1.4  2002/08/14 17:13:07  thomas
# 0.2.9 release
#
# Revision 1.3  2002/07/23 16:02:27  thomas
# version 0.2.5
#
# Revision 1.2  2002/07/08 15:56:33  thomas
# 0.2.3 release
#
# Revision 1.1.1.1  2002/05/21 14:13:28  thomas
# sushi - backup to disk
#

package Sushi::Limits;

use strict;
use Data::Dumper;


###############################################################################
# Verify that this record is valid.  1==good, 0==bad

sub checkAdd {
  my $parms = shift;
  my $opts = shift;
  my $table_def = shift;

  # Check to see if there are overlapping times specified
  my $ps = Sushi::Misc::db2sec ($parms->{start_time});
  my $pe = Sushi::Misc::db2sec ($parms->{end_time});
  if ($ps > $pe) {
    $main::log->error ("AddLimit: Start time must be before end time.\n");
    return 0;
  }
  my ($ds, $de);
  foreach (@{Sushi::GenDB::fetch ( {
				    resource_type => $parms->{resource_type},
				    resource_name => $parms->{resource_name}
				   },
				   $opts,
				   $table_def
				 )}) {
    $ds = Sushi::Misc::db2sec ($_->{start_time});
    $de = Sushi::Misc::db2sec ($_->{end_time});
    if (($ps>=$ds && $ps<=$de) ||
	($pe>=$ds && $pe<=$de) ||
	($ds>=$ps && $ds<=$pe) ||
	($de>=$ps && $de<=$pe)) {
      $main::log->error ("limit check: Start/End time conflict with existing limit.\n");
      return 0;
    }
  }
  # Looks good to me
  return 1;
}

###############################################################################
# Return a hash ref of active limits.  Index is the resource name,
# value is the total of the resource in all active atoms.

sub getActive {

  my $list = {};
  my $row;

  my $query = "select atom.id, resource_type, resource_name, weight from atom, atom_weights where state = 'Active' and atom.id = atom_weights.id ";
  $main::log->log (4, "Limits::getAliases $query\n");
  my $sth = $::sudbh->prepare ($query) or return undef;
  $sth->execute or return undef;
  while (defined ($row = $sth->fetchrow_hashref)) {
    if (!defined ($row->{resource_name}) || $row->{resource_name} eq "" ) {
      $main::log->error ("Yikes! (Un-)aliased resource $row->{resource_alias} in active atom $row->{id}.\n");
      next;
    }
    my $reskey = "$row->{resource_type}:$row->{resource_name}";
    defined ($list->{$reskey}) or $list->{$reskey}=0;
    $list->{$reskey} += $row->{weight};
  }
  return $list;
}

###############################################################################

1;
