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


# je potreba udelat obecne tak, aby uzivatel mohl zadavat atributy, ktere chce videt, formou u:d:Organization atp.

sub help {
	return qq{
	Prints list of group members and values of selected attributes. Group is required field. Group can by specified by it's ID or by both it's name and VO.
	---------------------------------
	Available options:
	--groupId      | -g  Group identifier
	--groupName    | -G  Group name
	--voId         | -v  VO identifier
	--voShortName  | -V  VO short name
	--attrList     | -a  list of attributes to print *)
	--statuses     | -s  list of allowed statuses   **)
	--orderByName  | -n  order by member's name
	--batch        | -b  batch
	--help         | -h  prints this help

		*) names of attributes are required in short form like
		   u:d:organization = urn:perun:user:attribute-def:def:organization,
		   m:d:organization = urn:perun:member:attribute-def:def:organization
		   u:d:preferredMail = urn:perun:user:attribute-def:def:preferredMail
		   ...
		   default value -a u:d:preferredMail m:d:organization
		**)if parameter -s is not used the default value is
		   VALID+INVALID
		   if parameter -s is used but the list of statuses is empty
		   ALL statuses are listed
	};
}

our $batch;
my ($groupId, $groupName, $voId, $voShortName, $sortingFunction, @attributes, @statuses);
GetOptions("help|h"       => sub {
		print help;
		exit 0;
	},
	"groupId|g=i"         => \$groupId,
	"groupName|G=s"       => \$groupName,
	"voId|v=i"            => \$voId,
	"voShortName|V=s"     => \$voShortName,
	'attrList|am=s@{1,}'  => \@attributes,
	'statuses|s=s@{0,}'   => \@statuses,
	"orderByName|n"       => sub { $sortingFunction = getSortingFunction("getLastName", 1) },
	"batch|b"             => \$batch) || die help;

my $agent = Perun::Agent->new();
my $groupsAgent = $agent->getGroupsAgent;
my $attributesAgent = $agent->getAttributesAgent;
my $membersAgent = $agent->getMembersAgent;

#options check
unless (defined $sortingFunction) { $sortingFunction = getSortingFunction("getLastName", 1); }
unless (defined $groupId) {
	unless (defined $groupName) { die "ERROR: Group specification required.\n"; }
	unless (defined $voId) {
		unless (defined $voShortName) { die "ERROR: VO specification required.\n"; }
		my $vo = $agent->getVosAgent->getVoByShortName( shortName => $voShortName );
		$voId = $vo->getId;
	}
	my $group = $groupsAgent->getGroupByName( vo => $voId, name => $groupName );
	$groupId = $group->getId;
}

unless (defined $statuses[0]) {
	@statuses = ("VALID", "INVALID");
}
if (defined $statuses[0] and $statuses[0] eq "") {
	@statuses = ();
}
foreach my $stat (@statuses) {
	if ($stat ne "VALID" and $stat ne "INVALID" and $stat ne "EXPIRED" and $stat ne "DISABLED") {die "ERROR: wrong status value. \n";}
}

my $parentGroup = 0;
my %attrShort;
my %entities = ("u" => "user", "m" => "member");
my %types = ("d" => "def", "o" => "opt", "v" => "virt", "c" => "core");

unless (@attributes) {
	@attributes = ("u:d:preferredMail", "m:d:organization");
}
foreach my $attr (@attributes) {
	my $attrName = "urn:perun:";
	if ($attr =~ /^(\w)\:(\w)\:([\w\:-]+)$/) {
		$attrName = $attrName.$entities{$1}.":attribute-def:".$types{$2}.":".$3;
		$attrShort{$attr} = $attrName;
	} else {
		printMessage "Wrong attribute name: $attr", $batch;
	}
}

my @richMembers = $membersAgent->getCompleteRichMembers( group => $groupId, attrsNames => [ values %attrShort ],
	allowedStatuses                                            => \@statuses, lookingInParentGroup => $parentGroup );
unless (@richMembers) {
	printMessage "No member found", $batch;
	exit 0;
}

#output
my @rows = ();
foreach my $richMember (sort $sortingFunction @richMembers) {
	my @uattributes = $richMember->getUserAttributes;
	my @mattributes = $richMember->getMemberAttributes;
	my @dispAtt;

	foreach my $shnam (sort keys (%attrShort)) {
		foreach my $ua (@uattributes) {
			if ($attrShort{$shnam} eq $ua->getName) {
				push (@dispAtt, $ua->getValueAsScalar);
			}
		}
		foreach my $ma (@mattributes) {
			if ($attrShort{$shnam} eq $ma->getName) {
				push (@dispAtt, $ma->getValueAsScalar);
			}
		}
	}
	my @row = ($richMember->getDisplayName, $richMember->getStatus, @dispAtt);
	push( @rows, \@row );
}

my @columnsNames = ( 'Name', 'Status', sort keys(%attrShort) );
print tableContentToPrint( \@columnsNames, \@rows, $batch );

