#!/usr/bin/perl

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

sub help {
	return qq{
	Sets the user facility attribute. Facility id or name, user id and attribute value and attribute id or name are required.
	---------------------------------------------------------------
	Available options:
	--facilityId      | -f facility id
	--facilityName    | -F facility name
	--userId          | -u user id
	--attributeId     | -a attribute id
	--attributeName   | -A attribute name including namespace
	--attributeValue  | -w attribute value
	--batch           | -b batch
	--help            | -h prints this help

	};
}

my ($facilityId, $facilityName, $attributeId, $attributeName, @attributeValue, $userId);
our $batch;
GetOptions ("help|h"    => sub {
		print help();
		exit 0;
	}, "batch|b"        => \$batch,
	"facilityId|f=i"    => \$facilityId,
	"facilityName|F=s"  => \$facilityName,
	"userId|u=i"        => \$userId,
	"attributeId|a=i"   => \$attributeId,
	"attributeName|A=s" => \$attributeName, 'attributeValue|w=s@{1,}' => \@attributeValue) || die help();

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

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

my $attributesAgent = $agent->getAttributesAgent;
my $attributeDefinition;

if (!defined($attributeId)) {
	$attributeDefinition = $attributesAgent->getAttributeDefinition( attributeName => $attributeName );
} else {
	$attributeDefinition = $attributesAgent->getAttributeDefinitionById( id => $attributeId );
}

# Get the attribute definition and create the attribute
my $attribute = Perun::beans::Attribute->fromAttributeDefinition( $attributeDefinition );

$attribute->setValueFromArray( @attributeValue );

$attributesAgent->setAttribute( facility => $facilityId, user => $userId, attribute => $attribute );

printMessage("Attribute Id:".$attribute->getId." set for the user Id: $userId and the facility Id: $facilityId",
	$batch);
