#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long qw(:config no_ignore_case);
use Perun::Agent;
use Perun::Common qw(printMessage);

sub help {
	return qq{
	Updates NotifReceiver. Id is required field.
	--------------------------------------
	Available options:
	--NotifReceiverId      | -i id of the NotifReceiver
	--target               | -r target
	--typeOfReceiver       | -t type of receiver (EMAIL_USER / EMAIL_GROUP / JABBER)
	--templateId           | -p template id (template has to exist)
	--locale 		       | -l locale
	--batch                | -b batch
	--help                 | -h prints this help

};
}

our $batch;
my ($id, $target, $type, $templateId, $locale);
GetOptions ("help|h" => sub {
		print help();
		exit 0;
	}, "batch|b"     => \$batch, "NotifReceiverId|i=i" => \$id,
	"target|r=s"     => \$target, "typeOfReceiver|t=s" => \$type, "templateId|p=i" => \$templateId, "locale|l=s" =>
	\$locale) || die help();

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

if (!defined($id)) { die "ERROR: id is required field\n";}

my $receiver = $notifAgent->getPerunNotifReceiverById( id => $id );

if (defined($target)) {
	unless ($target !~ /^\s*$/) { die "ERROR: target cannot be empty string\n";}
	$receiver->setTarget( $target );
}

if (defined($type)) {
	unless ($type !~ /^\s*$/) { die "ERROR: typeOfReceiver cannot be empty string\n";}
	if (($type !~ /^EMAIL_USER$/) and ($type !~ /^EMAIL_GROUP$/) and ($type !~ /^JABBER$/)) { die "ERROR: allowed typeOfReceiver values are only 'EMAIL_USER', 'EMAIL_GROUP' and 'JABBER'\n";}
	$receiver->setType( $type );
}

if (defined($templateId)) {
	$receiver->setTemplateId( $templateId );
}

if (defined($locale)) {
	$receiver->setLocale( $locale );
}

$receiver = $notifAgent->updatePerunNotifReceiver( receiver => $receiver );

printMessage("NotifReceiver Id:$id successfully updated", $batch);
