var params = JSON.parse(value);

var request = new HttpRequest();

request.addHeader('Content-Type: application/json');
request.addHeader('Authorization: Token ' + params.token);

var response,
	error_msg = '',
	enterprises = [],
	edges = [],
	links = [],
	gateways = [],
	version = [];

function getHttpData(url, body) {
	response = request.post(url, body);
	Zabbix.log(4, '[ SD-WAN API ] [ ' + url + ' ] Received response with status code ' + request.getStatus() + ': ' + response);

	if (response !== null) {
		try {
			response = JSON.parse(response);
		}
		catch (error) {
			throw 'Failed to parse response received from SD-WAN API. Check debug log for more information.';
		}
	}

	if (request.getStatus() !== 200) {
		if (response.error && response.error.message) {
			throw response.error.message;
		} else {
			throw 'Failed to receive data: invalid response status code.';
		}
	}

	if (typeof (response) !== 'object' || response === null) {
		throw 'Cannot process response data: received data is not an object.';
	}

	return response;
};

try {

	if (params.token === '{' + '$VELOCLOUD.TOKEN}') {
		throw 'Please change {' + '$VELOCLOUD.TOKEN} macro with the proper value.';
	}

	if (params.url.indexOf('http://') === -1 && params.url.indexOf('https://') === -1) {
		params.url = 'https://' + params.url;
	}

	if (!params.url.endsWith('/')) {
		params.url += '/';
	}

	enterprises = getHttpData(params.url + 'portal/rest/monitoring/getAggregates', '{}').enterprises;

	if (!Array.isArray(enterprises)) {
		throw 'Cannot process edges: enterprises is not an array.';
	}

	links = getHttpData(params.url + 'portal/rest/monitoring/getAggregateEdgeLinkMetrics', '{}');
	gateways = getHttpData(params.url + 'portal/rest/network/getNetworkGateways', JSON.stringify({ with: ['site'] }));
	version = getHttpData(params.url + 'portal/rest/system/getVersionInfo', '{}');

	for (var i in enterprises) {
		responseEdges = getHttpData(params.url + 'portal/rest/enterprise/getEnterpriseEdges', JSON.stringify({ enterpriseId: enterprises[i].id, with: ['site'] }));
		edges = edges.concat(responseEdges);
	}

} catch (error) {
	error_msg = error;
};

return JSON.stringify({
	'enterprises': enterprises,
	'edges': edges,
	'links': links,
	'gateways': gateways,
	'info': version,
	'error': error_msg.toString()
});