#!/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 Perun::beans::Destination;

sub help {
	return qq{
	Prints list of Destinations used for Facility and Service. Facility and service are required fields.
	---------------------------------------------------------------
	Available options:
	--facilityId   | -f  facility identifier
	--facilityName | -F  facility name
	--serviceId    | -s  service identifier
	--batch        | -b  batch
	--help         | -h  prints this help
	};
}


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

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

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

		 unless($facilityId) {
			 my $facilitiesAgent = $agent->getFacilitiesAgent;
			 my $facility = $facilitiesAgent->getFacilityByName(name => $facilityName);
			 $facilityId=$facility->getId;
		 }

		 my $servicesAgent = $agent->getServicesAgent;

		 my @destinations = $servicesAgent->getDestinations(facility => $facilityId, service => $serviceId);
		 unless(@destinations) { printMessage "No destinations found", $batch; exit 0;}

#output
		 my $table = Text::ASCIITable->new();
		 $table->setCols('ID', 'Destination', 'Type');

		 foreach my $destination (@destinations) {
			 $table->addRow($destination->getId, $destination->getDestination, $destination->getType);
		 }

		 print tableToPrint($table, $batch);
