#!/usr/bin/perl

use strict;
use warnings;
use Time::Local;
use Getopt::Long qw(:config no_ignore_case);
use Perun::Agent;
use Perun::Common qw(printMessage);
use Switch;

sub help {
	return qq{
	Sets the resource or facility ban. Resource and member Id OR facility and user Id required. Date (DD.MM.YYYY) OR time (in UNIX epoch) of ban validityTo required.
	---------------------------------------------------------------
	Available options:
        --valTo           | -v date of expiration of Ban (DD.MM.YYYY)
        --valToEpoch      | -t time (in UNIX epoch in ms)
        --resource        | -r resource Id
        --member          | -m member Id
        --facility        | -f facility Id
        --user            | -u user Id
        --description     | -d description of Ban
	--batch           | -b batch
	--help            | -h prints this help

	};
}

my ($valTo, $valToEpoch, $resourceId, $memberId, $facilityId, $userId, $dsc);
our $batch;
GetOptions ("help|h"  => sub {
		print help();
		exit 0;
	}, "batch|b"      => \$batch,
	"valTo|v=s"       => \$valTo,
	"valToEpoch|t=i"  => \$valToEpoch,
	"resource|r=i"    => \$resourceId,
	"member|m=i"      => \$memberId,
	"facility|f=i"    => \$facilityId,
	"user|u=i"        => \$userId,
	"description|d=s" => \$dsc) || die help();

# Check options
unless (defined($valTo) or defined($valToEpoch)) { die "ERROR: valTo or valToEpoch is required \n";}
unless (defined($resourceId) or defined($facilityId)) { die "ERROR: resource or facility is required \n";}
if (defined($resourceId) and !defined($memberId)) { die "ERROR: member Id is required in case of using resource \n";}
if (defined($facilityId) and !defined($userId)) { die "ERROR: user Id is required in case of using facility \n";}

my $agent = Perun::Agent->new();
if (defined $valTo and !defined $valToEpoch) {
	my ($dd, $mm, $rr) = split(/\./, $valTo);
	$valToEpoch = timelocal(0, 0, 0, $dd * 1, $mm * 1 - 1, $rr * 1 - 1900) * 1000;
}
if (defined($resourceId)) {
	my $BanOnResourceAgent = $agent->getBanOnResourceAgent;
	my $ban = Perun::beans::BanOnResource->new;
	$ban->setId( 0 );
	$ban->setValidityTo( $valToEpoch );
	$ban->setResourceId( $resourceId );
	$ban->setMemberId( $memberId );
	$ban->setDescription( $dsc ) if defined($dsc);
	$ban = $BanOnResourceAgent->setBan( banOnResource => $ban );
	printMessage("Ban Id: ".$ban->getId." set for resource $resourceId and member $memberId.", $batch);
}

if (defined($facilityId)) {
	my $BanOnFacilityAgent = $agent->getBanOnFacilityAgent;
	my $ban = Perun::beans::BanOnFacility->new;
	$ban->setId( 0 );
	$ban->setValidityTo( $valToEpoch );
	$ban->setFacilityId( $facilityId );
	$ban->setUserId( $userId );
	$ban->setDescription( $dsc ) if defined($dsc);
	$ban = $BanOnFacilityAgent->setBan( banOnFacility => $ban );
	printMessage("Ban Id: ".$ban->getId." set for facility $facilityId and user $userId.", $batch);

}  

