var edges = JSON.parse(value).edges,
	token = '{$VELOCLOUD.TOKEN}',
	url = '{$VELOCLOUD.URL}';

var request = new HttpRequest();

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

var response,
	error_msg = '',
	edges = [],
	edgeSDWan = [],
	edgeSDWanPath = [];

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 (token === '{' + '$VELOCLOUD.TOKEN}') {
		throw 'Please change {' + '$VELOCLOUD.TOKEN} macro with the proper value.';
	}

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

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

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

	for (var i in edges) {
		responseEdgeSDWan = getHttpData(url + 'portal/rest/edge/getEdgeSDWANPeers', JSON.stringify({ enterpriseId: edges[i].enterpriseId, edgeId: edges[i].id }));

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

		for (var e in responseEdgeSDWan) {
			data = {
				'enterpriseId': edges[i].enterpriseId,
				'edgeId': edges[i].id,
				'peerLogicalId': responseEdgeSDWan[e].deviceLogicalId
			};
			responseEdgeSDWanPath = getHttpData(url + 'portal/rest/metrics/getEdgeSDWANPeerPathMetrics', JSON.stringify(data));
			edgeSDWanPath = edgeSDWanPath.concat(responseEdgeSDWanPath);

			responseEdgeSDWan[e].edgeId = edges[i].id;
			responseEdgeSDWan[e].edgeName = edges[i].name;
			responseEdgeSDWan[e].enterpriseId = edges[i].enterpriseId;
		}

		edgeSDWan = edgeSDWan.concat(responseEdgeSDWan);
	}

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

return JSON.stringify({
	'edgeSDWan': edgeSDWan,
	'edgeSDWanPath': edgeSDWanPath,
	'error': error_msg.toString()
});