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

sub help {
	return qq{
	Find users by attribute.
	------------------------
	Available options:
	--attributeName   | -a attribute name
	--attributeValue  | -w attribute value
	--orderByName     | -n  order by user's name
	--batch           | -b batch
	--help            | -h prints this help

	};
}

my ($attributeName, @attributeValue, $sortingFunction, $batch);
GetOptions ("help|h"    => sub {
		print help();
		exit 0;
	}, "batch|b"        => \$batch,
	"attributeName|a=s" => \$attributeName, 'attributeValue|w=s@{1,}' => \@attributeValue,
	"orderByName|n"     => sub { $sortingFunction = getSortingFunction("getLastName", 1) } ) || die help();

# Check options
unless (defined($attributeName)) { die "ERROR: attributeName is required \n";}
unless (@attributeValue) { die "ERROR: attributeValue is required \n";}

#options check
unless (defined $sortingFunction) { $sortingFunction = getSortingFunction("getLastName", 1); }

my $agent = Perun::Agent->new();
my $usersAgent = $agent->getUsersAgent;
my $attributesAgent = $agent->getAttributesAgent;

my $attributeDefinition = $attributesAgent->getAttributeDefinition( attributeName => $attributeName );
my $attribute = Perun::beans::Attribute->fromAttributeDefinition( $attributeDefinition );
$attribute->setValueFromArray( @attributeValue );

my @users = $usersAgent->getUsersByAttribute( attributeName => $attributeName, attributeValue => $attribute->getValue );

#output
my @rows = ();
foreach my $user (sort $sortingFunction @users) {
	my $name = $user->getFirstName." ".($user->getMiddleName ? $user->getMiddleName." " : "" ).$user->getLastName;
	my @row = ($user->getId, $name);
	push(@rows, \@row);
}

my @columnsNames = ('ID', 'Name');
print tableContentToPrint(\@columnsNames, \@rows, $batch);
