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

sub help {
	return qq{
	Lists all required member resource attributes. Resource id and member id are required options.
	-----------------------------------------------------------------------
	Available options:
	--resourceId   | -r resource id
	--memberId     | -m member id
	--optionUseRes | -o option for using 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 ($resourceId, $memberId, $opt, $sortingFunction);
GetOptions ("help|h" => sub {
		print help();
		exit 0;
	}, "batch|b"     => \$batch,
	"resourceId|r=i" => \$resourceId,
	"memberId|m=i"   => \$memberId,
	"optionUseRes|o" => \$opt,
	"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($resourceId)) { die "ERROR: resourceId is required \n";}
unless (defined($memberId)) { die "ERROR: memberId is required \n";}

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

my $attributesAgent = $agent->getAttributesAgent;
my @attributes;
if ($opt) {
	@attributes = $attributesAgent->getRequiredAttributes( resource => $resourceId, member => $memberId,
		resourceToGetServicesFrom                                   => $resourceId );
} else {
	@attributes = $attributesAgent->getRequiredAttributes( resource => $resourceId, member => $memberId );
}

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

printTable($sortingFunction, @attributes);
