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

sub help {
	return qq{
	Prints list of members found by searching through user attributes. Need to specify vo where will be members looking for.
	---------------------------------
	Available options:
	--voId        | -v  VO idetifier
	--voShortName | -V  VO short name
	--mapOfAttrs  | -m  Map with attr_names and values for searching
	--batch       | -b  batch
	--help        | -h  prints this help

	};
}

our $batch;
my ($voId, $voShortName, @mapOfAttrs, $sortingFunction);
GetOptions("help|h"       => sub {
		print help;
		exit 0;
	},
	"voId|v=i"            => \$voId,
	"voShortName|V=s"     => \$voShortName,
	'mapOfAttrs|m=s@{1,}' => \@mapOfAttrs,
	"batch|b"             => \$batch) || die help;

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

#options check
unless (defined $sortingFunction) { $sortingFunction = getSortingFunction("getMemberId"); }
unless (defined $voId) {
	unless (defined $voShortName) { die "ERROR: VO specification required.\n"; }
	my $vo = $agent->getVosAgent->getVoByShortName( shortName => $voShortName );
	$voId = $vo->getId;
}

my %mapOfAttrs = @mapOfAttrs;
my @members = $searcherAgent->getMembersByUserAttributes( vo => $voId, userAttributesWithSearchingValues =>
	\%mapOfAttrs );
unless (@members) {
	printMessage "No member found", $batch;
	exit 0;
}

#output
printTable($sortingFunction, @members);
