package Client::Advisor;
use Client;
use LockManager;
use Util::Http;
use Events;

sub reserve_status {
  my($q) = @_;
  print Client->http_OK();
  my $lock = LockManager->new();
  my $key = "system";
  if (defined($q->{key})) {
    $key = $q->{key};
  }
  my $locki = $lock->exists($key, 1) || {};
  if ($locki->{pid}) {
    my ($app, $key, $desc, $start, $mins, $ip, $name) = split(/\|/, $locki->{info});
    my $hours = int($mins / 60);
    $desc = Client->xmlEncode($desc);
    print "<RESERVE_STATUS>\n";
    print "<STATUS>Yes</STATUS>\n";
    print "<NAME>$name</NAME>\n";
    print "<DESC>$desc</DESC>\n";
    print "<TIME>$hours</TIME>\n";
    print "</RESERVE_STATUS>\n";
  } else {
    print "<RESERVE_STATUS>\n";
    print "<STATUS>No</STATUS>\n";
    print "</RESERVE_STATUS>\n";
  }
}

#
# Reverse a resource
# key : the key of the resource (e.g., a device)
# name : the person doing the reservation.
# desc : the description the reservation is for.
# expires : how long is the reservation for. (in minutes)
# force : 0 (do not force) or 1 (force)
#
sub reserve {
  my($q) = @_;
  my $key = "system";
  if (defined($q->{key})) {
    $key = $q->{key};
  }
  print Client->http_OK();
  if (!$q->{name} || !$q->{desc}) {
    # parameters missing to reserve
    print "<STATUS>ERROR</STATUS>\n";
  } else {
    my $lock = LockManager->new();
    my $time = 60*60 * ($q->{expires}||1);
    my $ip   = $ENV{REMOTE_ADDR} || $ENV{REMOTE_USER};
    my $mins = $q->{expires} * 60;
    my $info = "service|$q->{key}|$q->{desc}|" . Util->get_today() . "|$mins|$ip|$q->{name}";
    my $force = $q->{force};
    my $rc = $lock->lock($key, $time, 0, $info, {force => $force});
    Events->saveEvent("SR", $info); # service-reserve
    print Client->http_OK();
    print "<STATUS>OK</STATUS>\n";
  }
}

#set the lease time to ten minutes and Agent/SE_MODULE.pm will clean up later
sub release {
  my($q) = @_;
  my $key = "system";
  if (defined($q->{key})) {
    $key = $q->{key};
  }
  my $lock = LockManager->new();
  my $current = $lock->read($key);
  my $rc = $lock->unlock($key);
  # 6293541: limit the following code to System Edition, 
  # which is what it intended to fix for bug 6260099
  if (!defined($q->{key})) {
    $rc = $lock->lock($key, 600, 0, $current->{info}, {force => $force});
  }
  Events->saveEvent("SL", $current->{info}); # service-release
  print Client->http_OK();
  print "<STATUS>OK</STATUS>\n";
}

1;

