var VeloCloud = {
	params: {},

	setParams: function (params) {
		['url', 'token'].forEach(function (field) {
			if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
				throw 'Required param is not set: ' + field + '.';
			}
		});

		VeloCloud.params = params;

		if (VeloCloud.params.token === '{' + '$VELOCLOUD.TOKEN}') {
			throw 'Please change {' + '$VELOCLOUD.TOKEN} macro with the proper value.';
		}
		if (!VeloCloud.params.url.startsWith('http://') && !VeloCloud.params.url.startsWith('https://')) {
			VeloCloud.params.url = 'https://' + params.url;
		}
		if (!VeloCloud.params.url.endsWith('/')) {
			VeloCloud.params.url += '/';
		}

	},

	getField: function (data, path, trace) {
		const steps = path.split('.');

		for (var i = 0; i < steps.length; i++) {
			var step = steps[i];
			if (typeof data !== 'object' || typeof data[step] === 'undefined') {
				throw 'Required field was not found: ' + path + ' - ' + trace;
			}
			data = data[step];
		}

		return data;
	},

	request: function (url, body) {

		var response, request = new HttpRequest();

		if (typeof VeloCloud.params.http_proxy !== 'undefined' && VeloCloud.params.http_proxy !== '') {
			request.setProxy(VeloCloud.params.http_proxy);
		}

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

		response = request.post(url, body);

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

		if (request.getStatus() !== 200 || response === null) {
			throw 'Request failed with status code ' + request.getStatus() + ': ' + response;
		}
		try {
			response = JSON.parse(response);
		}
		catch (error) {
			throw 'Failed to parse response received from SD-WAN API. Check debug log for more information.';
		}
		if (response.error && response.error.message) {
			throw response.error.message;
		}

		return response;

	},

	getMetricsData: function () {
		var edge_sdwan = [],
			edge_sdwan_path = [];


		response_edge_sdwan = VeloCloud.request(VeloCloud.params.url + 'portal/rest/edge/getEdgeSDWANPeers', JSON.stringify({ enterpriseId: Number(VeloCloud.params.enterprise_id), edgeId: Number(VeloCloud.params.edge_id) }));

		if (!Array.isArray(response_edge_sdwan)) {
			response_edge_sdwan = [response_edge_sdwan];
		}

		for (var e in response_edge_sdwan) {
			data = {
				enterpriseId: Number(VeloCloud.params.enterprise_id),
				edgeId: Number(VeloCloud.params.edge_id),
				peerLogicalId: VeloCloud.getField(response_edge_sdwan[e], 'deviceLogicalId', 'error get peerLogicalId')
			};
			response_edge_sdwan_path = VeloCloud.request(VeloCloud.params.url + 'portal/rest/metrics/getEdgeSDWANPeerPathMetrics', JSON.stringify(data));
			edge_sdwan_path = edge_sdwan_path.concat(response_edge_sdwan_path);

			response_edge_sdwan[e].edgeId = Number(VeloCloud.params.edge_id);
			response_edge_sdwan[e].edgeName = VeloCloud.params.edge_name;
			response_edge_sdwan[e].enterpriseId = Number(VeloCloud.params.enterprise_id);
		}

		edge_sdwan = edge_sdwan.concat(response_edge_sdwan);

		return { edgeSDWan: edge_sdwan, edgeSDWanPath: edge_sdwan_path };

	}
}

try {
	VeloCloud.setParams(JSON.parse(value));
	return JSON.stringify(VeloCloud.getMetricsData());
}
catch (error) {
	error += (String(error).endsWith('.')) ? '' : '.';
	Zabbix.log(3, '[ VeloCloud ] ERROR: ' + error);
	return JSON.stringify({ 'error': error });
}