#!/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{
	Lists all required facility attributes. Facility id or name is required option.
	-----------------------------------------------------------------------
	Available options:
	--facilityId   | -f facility id
	--facilityName | -F facility name
	--orderById    | -i order by attribute id
	--orderByName  | -n order by attribute friendly name
	--batch        | -b batch
	--help         | -h help

	};
}

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

unless(defined $sortingFunction) { $sortingFunction = getSortingFunction("getFriendlyName", 1); }

# Check options
unless (defined($facilityId) or (defined($facilityName))) { die "ERROR: facilityId or facilityName is required \n";}

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

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

my $attributesAgent = $agent->getAttributesAgent;
my @attributes = $attributesAgent->getRequiredAttributes(facility => $facilityId);

unless(@attributes) { printMessage "No required attributes found", $batch;  exit 0; }

my $table = Text::ASCIITable->new();
$table->setCols('attribute Id','attribute friendly name','namespace', 'value');

foreach my $attribute (sort $sortingFunction @attributes) {
	$table->addRow($attribute->getId, $attribute->getFriendlyName, $attribute->getNamespace, $attribute->getValueAsScalar);
}
print tableToPrint($table, $batch);
