var params = JSON.parse(value),
	request = new HttpRequest(),
	device_info = {},
	error_msg = "";

function getHttpData(url, token, cookie) {
	request.addHeader('Cookie: ' + cookie);
	request.addHeader('X-XSRF-TOKEN: ' + token);
	response = request.get(url);
	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);
	}

	device_info = getHttpData(
		params.url + 'dataservice/device?deviceId=' + encodeURIComponent(params.device_id),
		params.token,
		params.cookie
	);

	if (Array.isArray(device_info.data) && device_info.data.length > 0) {
		device_info = device_info.data[0];
	}
	else {
		throw 'Failed to parse response received from Cisco SD-WAN API. Check debug log for more information.';
	}

	var system_info = getHttpData(
		params.url + 'dataservice/device/system/status?deviceId=' + params.device_id,
		params.token,
		params.cookie
	);

	if (Array.isArray(system_info.data) && system_info.data.length > 0) {
		device_info = Object.assign(device_info, system_info.data[0]);
	}
	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);
};

device_info.error = error_msg;

return JSON.stringify(device_info);