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

sub help {
	return qq{
	Lists all required user attributes. User id is required option. Resource id is optional.
	-----------------------------------------------------------------------
	Available options:
	--userId       | -u user id
	--resourceId   | -r resource to get services from
	--orderById    | -i order by attribute id
	--orderByName  | -n order by attribute friendly name
	--batch        | -b batch
	--help         | -h help

	};
}

our $batch;
my ($userId, $resourceId, $sortingFunction);
GetOptions ("help|h" => sub {
		print help();
		exit 0;
	}, "batch|b"     => \$batch,
	"userId|u=i"     => \$userId,
	"resourceId|r=i" => \$resourceId,
	"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($userId)) { die "ERROR: userId is required \n";}

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

my $attributesAgent = $agent->getAttributesAgent;

my @attributes;
if ($resourceId) {
	@attributes = $attributesAgent->getResourceRequiredAttributes( user => $userId, resourceToGetServicesFrom =>
		$resourceId );
} else {
	@attributes = $attributesAgent->getRequiredAttributes( user => $userId );
}

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

printTable($sortingFunction, @attributes);
