#!/usr/bin/perl -w

use strict;
use warnings;
use Getopt::Long qw(:config no_ignore_case);
use Text::ASCIITable;
use Perun::Agent;
use Perun::Common qw(printMessage tableToPrint getSortingFunction);

sub help {
	return qq{
	Prints list of VOs which are allowed to use Facility. Facility is required field.
	---------------------------------------------------------
	Available options:
	--facilityId   | -f  facility identifier
	--facilityName | -F  facility name
	--orderById    | -i  order by numeric id
	--orderByName  | -n  order by short name (default)
	--batch        | -b  batch
	--help         | -h  prints this help
	};
}

my ($facilityId, $facilityName, $batch, $sortingFunction);
GetOptions("help|h" => sub { print help; exit 0;} ,
					"facilityId|f=i" => \$facilityId,
					"facilityName|F=s" => \$facilityName,
					"orderById|i" => sub { $sortingFunction = getSortingFunction("getId") } ,
					"orderByName|n" =>  sub {$sortingFunction = getSortingFunction("getShortName", 1) },
					"batch|b" => \$batch) || die help;

#options check
			 unless(defined($facilityId) or (defined($facilityName))) { die "ERROR: facilityId or facilityName is required\n";}
			 unless(defined $sortingFunction) { $sortingFunction = getSortingFunction("getShortName", 1); }

			 my $agent = Perun::Agent->new();
			 my $facAgent = $agent->getFacilitiesAgent;

			 unless($facilityId) {
				 my $facility = $facAgent->getFacilityByName(name => $facilityName);
				 $facilityId = $facility->getId;
			 }

			 my @vos = $facAgent->getAllowedVos(facility=>$facilityId);


#output
			 unless(@vos) { printMessage "No VOs assigned", $batch; exit 0; }
			 my $table = Text::ASCIITable->new();
			 $table->setCols('VO id','VO shortName');

			 foreach my $vo (sort $sortingFunction @vos) {
				 $table->addRow($vo->getId, $vo->getShortName);
			 }

			 print tableToPrint($table, $batch);