#!/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{
	Displayes BlackList at Facility. Facility Id or name are required fields.
	------------------------------------
	Available options:
	--facilityId     | -f facility Id 
        --facilityName   | -F  facility name
        --orderById      | -i order by user's identifier
        --orderByName    | -n order by user's name
	--batch          | -b batch
	--help           | -h prints this help

	};
}

my ($facilityId, $facilityName, $batch, $sortingFunction);
GetOptions ("help|h"   => sub {
		print help();
		exit 0;
	}, "batch|b"       => \$batch,
	"orderById|i"      => sub { $sortingFunction = getSortingFunction("getId") },
	"orderByName|n"    => sub { $sortingFunction = getSortingFunction("getLastName", 1) },
	"facilityName|F=s" => \$facilityName,
	"facilityId|f=i"   => \$facilityId || die help());

# Check options
unless (defined $facilityId or (defined $facilityName)) { die "ERROR: facilityId or facilityName is required\n";}
unless (defined $sortingFunction) { $sortingFunction = getSortingFunction("getLastName", 1); }

my $agent = Perun::Agent->new();
my $securityTeamsAgent = $agent->getSecurityTeamsAgent;
unless ($facilityId) {
	my $facilitiesAgent = $agent->getFacilitiesAgent;
	my $facility = $facilitiesAgent->getFacilityByName( name => $facilityName );
	$facilityId = $facility->getId;
}

my @users = $securityTeamsAgent->getBlacklist( facility => $facilityId );
unless (@users) {
	printMessage "No blacklisted users found", $batch;
	exit 0;
}

#output
my @rows = ();
foreach my $user (sort $sortingFunction @users) {
	my @row = ($user->getId, $user->getCommonName);
	push(@rows, \@row);
}
my @columnsNames = ('User Id', 'User Name');
print tableContentToPrint(\@columnsNames, \@rows, $batch);
