#!/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 getSortingFunction tableContentToPrint);

sub help {
	return qq{
	Prints attribute policy collections for selected attribute.
	--------------------------------
	Available options:
	--attributeId     | -a  attribute identifier
	--attributeName   | -A  attribute name (including namespace)
	--help            | -h  prints this help
	};
}

my $sortingFunction = getSortingFunction("getAction", 1);

my ($attributeId, $attributeName);
GetOptions("help|h"   => sub {
	 	print help;
		exit 0;
	},
	"attributeId|a=i"       => \$attributeId,
	"attributeName|A=s"     => \$attributeName) || 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 $attributeRules;
$attributeRules = $attributesAgent->getAttributeRules( attributeDefinition => $attributeId );

#OUTPUT
print "Critical actions: ";
if (!$attributeRules->getCriticalActions) {
	print "None\n";
} else {
	print join(", ", $attributeRules->getCriticalActions) . "\n";
}
print "Policy collections: \n";
foreach my $collection (sort $sortingFunction $attributeRules->getAttributePolicyCollections) {
	my $table = Text::ASCIITable->new({ headingText => "".$collection->getAction});
	$table->setCols('Role','Object');
	foreach my $policy ($collection->getPolicies) {
		$table->addRow($policy->getRole, $policy->getObject);
		$table->addRowLine();
	}
	print $table;
}