#!/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);
#use Data::Dumper;

sub help {
	return qq{
	Prints attribute rights of roles
	--------------------------------
	Available options:
	--attributeId     | -a  attribute identifier
	--attributeName   | -A  attribute name (including namespace)
	--batch           | -b  batch
	--help            | -h  prints this help
	};
}

my ($attributeId, $attributeName, $batch);
GetOptions("help|h"   => sub {
	 	print help;
		exit 0;
	},
	"attributeId|a=i"       => \$attributeId,
	"attributeName|A=s"     => \$attributeName,
	"batch|b"               => \$batch) || die help;

#options check
unless (defined $attributeId or defined $attributeName) { die "ERROR: attributeId or attributeName are required\n";}

my $agent = Perun::Agent->new();
my $attributesAgent = $agent->getAttributesAgent;
my $attributeDefinition;
if (defined $attributeName and not defined $attributeId) {
	$attributeDefinition = $attributesAgent->getAttributeDefinition( attributeName => $attributeName );
	$attributeId=$attributeDefinition->getId;
}

my @rights;
@rights = $attributesAgent->getAttributeRights(attributeId => $attributeId);
#output
printMessage "\n.-----------------------------.\n| Attribute : ".$attributeId."\t      |", $batch;
my $table = Text::ASCIITable->new({ reportErrors => 0, utf8 => 0 });
$table->setCols('Role','Rights' );
foreach my $right (@rights) {
	#print Dumper($right);
	my @actions=$right->getRights;
	my $out="";
        if (defined $actions[0]) {
		$out=$out.$actions[0];
	} else {
		$out=$out."     ";
	}
	if (defined $actions[1]) {
		$out=$out." ".$actions[1];
	} else {
		$out=$out."      ";
	}
	$table->addRow($right->getRole,$out);
} 
print tableToPrint($table, $batch);

