#!/usr/bin/perl

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 Attributes defined on VO. VO is required field.
	---------------------------------------------------
	Available options:
	--voId         | -v  vo idetifier
	--voShortName  | -V  vo short name
	--orderById    | -i  order by numeric Id
	--orderByName  | -n  order by Name
	--batch        | -b  batch
	--help         | -h  prints this help
	};
}

my ($voId, $voShortName, $batch, $sortingFunction);
GetOptions("help|h" => sub { print help; exit 0;} ,
	"voId|v=i" => \$voId,
"voShortName|V=s" => \$voShortName,
					 "orderById|i" => sub { $sortingFunction = getSortingFunction("getId") } ,
					 "orderByName|n" =>  sub {$sortingFunction = getSortingFunction("getName", 1) },
					 "batch|b" => \$batch) || die help;

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

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

			 unless($voId) {
				 my $vosAgent = $agent->getVosAgent;
				 my $vo = $vosAgent->getVoByShortName(shortName => $voShortName);
				 $voId=$vo->getId;
			 }

			 my $attributesAgent = $agent->getAttributesAgent;

			 my @attributes = $attributesAgent->getAttributes(vo => $voId);
			 unless(@attributes) { printMessage "No Attribute found", $batch; exit 0;}


#output
			 my $table = Text::ASCIITable->new();
			 $table->setCols('ID','Name', 'Type', 'Value');

			 foreach my $attribute (sort $sortingFunction @attributes) {
				 $table->addRow($attribute->getId, $attribute->getName, $attribute->getType, $attribute->getValueAsScalar);
			 }

			 print tableToPrint($table, $batch);
