###########################################################################
# CLOUD SERVER API DOCUMENTATION
#
# Name: createLoadBalancer
# Language: Perl
#
# Description: this function creates a load balancer
###########################################################################
use strict;
use LWP::UserAgent;
use URI::Escape;
use JSON;
require Http::Request::Common;

#ID access to API
my $TOKEN = "{YOUR_API_TOKEN}"; # e.g.: "f03c3c76cc853ee690b879909c9c6f2a"
my $url = "https://cloudpanel-api.ionos.com/v1";

sub _createLoadBalancer
{
	my ($content) = @_;
	my $_command = $url ."/load_balancers";
	my $_method = 'POST';

	#Create the request
	my $ua = LWP::UserAgent->new;
	my $request = HTTP::Request->new($_method => $_command);
	$request->header('X-TOKEN' => $TOKEN);
	$request->content_type('application/json');
	
	#Add additional parameters
	$request->content($content);

	#Get the response
	my $response = $ua->request($request);

	if($response)
	{
		#Get the response and close the handlers
		print $response->headers()->as_string ."\n";
		return $response->content;
		$response->close;
		$request->close;
	}
	else
	{
		#Get the error and close the handlers
		return "Http Error Code: ", $response->code, "\n";
		$request->close;
	}			
}

#Parameters
my $name = "My load balancer";
my $description = "My load balancer description";
my $health_check_test = "TCP";
my $health_check_interval = 30;
my $persistence = "true";
my $persistence_time = 1200;
my $method = "ROUND_ROBIN";
my @_rules = [{"protocol" => "TCP", "port_balancer" => 90, "port_server" => 90}];

my %_query = ("name" => $name, 
              "description" => $description, 
              "health_check_test" => $health_check_test, 
              "health_check_interval" => $health_check_interval,
              "persistence" => $persistence,
              "persistence_time" => $persistence_time,
              "method" => $method,
              "rules" => @_rules);
              
my $query = encode_json \%_query;

#Create load balancer
print _createLoadBalancer($query);