#!/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 tableToPrint getSortingFunction);
#use Data::Dumper;

sub help {
        return qq{
        Lists SecurityTeams assigned to facility.
        --------------------------
        Available options:
        --facilityId   | -f facility id
        --facilityName | -F facility name
        --orderByName  | -n order by securityTeam name
        --orderBuId    | -i order by securityTeam id
        --batch        | -b batch
        --help         | -h prints this help

        };
}

my ($facilityId, $facilityName, $batch, $sortingFunction, $displayIds);

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

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

my $agent = Perun::Agent->new();
my $facilitiesAgent = $agent->getFacilitiesAgent;
 
my $facility;
if ($facilityId) {
    $facility = $facilitiesAgent->getFacilityById(id => $facilityId);
}
if ($facilityName) {
    $facility = $facilitiesAgent->getFacilityByName(name => $facilityName);
    $facilityId=$facility->getId;
}

my @securityTeams;
@securityTeams = $facilitiesAgent->getAssignedSecurityTeams(facility => $facilityId);
unless (@securityTeams) { printMessage "No securityTeams found", $batch; exit 0;} 

#output
my $table = Text::ASCIITable->new();

$table->setCols('Id','Name');

foreach my $securityTeam (sort $sortingFunction @securityTeams) {
    $table->addRow($securityTeam->getId(),$securityTeam->getName());
}
print tableToPrint($table, $batch);

