var params = JSON.parse(value),
	request = new HttpRequest(),
	result = { "data": [], "error": "" },
	error_msg = "";

function getHttpData(url, data, token, cookie) {
	request.addHeader('Cookie: ' + cookie);
	request.addHeader('Content-Type: application/json');
	request.addHeader('X-XSRF-TOKEN: ' + token);

	if (typeof data !== 'undefined') {
		data = JSON.stringify(data);
	}

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

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

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

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

	return response;
};

try {
	['auth.token', 'auth.cookie', 'api.url', 'device_id'].forEach(function (field) {
		var macro = '{$SDWAN.' + field.toUpperCase() + '}';
		var key = field.split('.').slice(-1);
		if (params[key] === macro || params[key] === '') {
			throw 'Please change ' + macro + ' macro to the proper value.';
		}
		if (typeof params[key] === 'undefined') {
			throw 'Please set \'' + key + '\' script input parameter to ' + macro + ' macro value.';
		}
	});

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

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

	if (typeof params.http_proxy !== 'undefined' && params.http_proxy !== '{' + '$SDWAN.HTTP_PROXY}' && params.http_proxy !== '') {
		request.setProxy(params.http_proxy);
	}

	if (!params.interval.endsWith('h')) {
		throw 'The value of {' + '$SDWAN.ROUTES.INTERVAL} must be expressed in hours.';
	}
	else {
		try {
			params.interval = Number(params.interval.replace('h', ''));
		}
		catch (error) {
			throw 'Please change {' + '$SDWAN.ROUTES.INTERVAL} macro to the proper value.';
		}
	}

	var req_data = {
		"query": {
			"condition": "AND",
			"rules": [
				{
					"value": [
						String(params.interval)
					],
					"field": "entry_time",
					"type": "date",
					"operator": "last_n_hours"
				},
				{
					"value": [
						params.device_id
					],
					"field": "vdevice_name",
					"type": "string",
					"operator": "in"
				}
			]
		},
		"aggregation": {
			"field": [
				{
					"property": "local_color",
					"order": "asc",
					"sequence": 1
				},
				{
					"property": "remote_color",
					"order": "asc",
					"sequence": 1
				}
			],
			"metrics": [
				{
					"property": "loss_percentage",
					"type": "avg"
				},
				{
					"property": "latency",
					"type": "avg"
				},
				{
					"property": "jitter",
					"type": "avg"
				}
			]
		}
	};

	var routes = getHttpData(
		params.url + 'dataservice/statistics/approute/aggregation',
		req_data,
		params.token,
		params.cookie
	);

	if (Array.isArray(routes.data)) {
		result["data"] = routes.data;
	}
	else {
		throw 'Failed to parse response received from Cisco SD-WAN API. Check debug log for more information.';
	}
} catch (error) {
	error_msg = error.toString();
	error_msg += (error_msg.endsWith('.')) ? '' : '.';
	Zabbix.log(3, '[ Cisco SD-WAN ] ERROR: ' + error_msg);
};

result.error = error_msg;

return JSON.stringify(result);