#!/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 selected attribute for an entity.
	---------------------------------------------------
	Available options:
	--userId       | -u  user identifier
	--facilityId   | -f  facility identifier
	--memberId     | -m  member identifier
	--resourceId   | -r  reource identifier
	--hostId       | -h  host identifier
	--groupId      | -g  group identifier
	--voId         | -v  vo identifier
	--attributeId  | -a  attribute identifier
	--orderById    | -i  order by numeric Id
	--orderByName  | -n  order by Name
	--batch        | -b  batch
	--help         | -h  prints this help
	};
}

my ($userId, $facilityId, $memberId, $resourceId, $groupId, $voId, $hostId, $attributeId, $batch, $sortingFunction);
GetOptions("help|h" => sub { print help; exit 0;} ,
	"userId|u=i" => \$userId,
"facilityId|f=i" => \$facilityId,
					 "memberId|m=i" => \$memberId,
				 "resourceId|r=i" => \$resourceId,
			 "groupId|g=i" => \$groupId,
		 "voId|v=i" => \$voId,
	 "hostId|h=i" => \$hostId,
 "attributeId|a=i" => \$attributeId,
					 "orderById|i" => sub { $sortingFunction = getSortingFunction("getId") } ,
					 "orderByName|n" =>  sub {$sortingFunction = getSortingFunction("getName", 1) },
					 "batch|b" => \$batch) || die help;

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

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

			 my $attributesAgent = $agent->getAttributesAgent;

			 my %parameters;
			 $parameters{attributeId} = $attributeId;
			 defined ($userId) and $parameters{user} = $userId;
			 defined ($facilityId) and $parameters{facility} = $facilityId;
			 defined ($memberId) and $parameters{member} = $memberId;
			 defined ($resourceId) and $parameters{resource} = $resourceId;
			 defined ($groupId) and $parameters{group} = $groupId;
			 defined ($voId) and $parameters{vo} = $voId;
			 defined ($hostId) and $parameters{host} = $hostId;

			 my @attributes = $attributesAgent->getAttribute(%parameters);

			 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);
