try {
	var creds = JSON.parse(value);
}
catch (error) {
	throw 'Failed to parse authentication data from input value.';
}

var request = new HttpRequest(),
	devices = [],
	error_msg = "",
	url = "{$SDWAN.API.URL}",
	http_proxy = "{$SDWAN.HTTP_PROXY}";

function getHttpData(url, token, cookie) {
	request.addHeader('Cookie: ' + cookie);
	request.addHeader('X-XSRF-TOKEN: ' + token);
	response = request.get(url);
	Zabbix.log(4, '[ SD-WAN API ] [ ' + 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 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 {

	['token', 'cookie'].forEach(function (field) {
		if (creds[field] === null || creds[field] == "" || typeof creds[field] === 'undefined') {
			throw 'Unexpected token value has been received'
			+ ((typeof creds.error !== 'undefined' && creds.error != "") ? ': ' + creds.error : '');
		}
	});

	if (url === '{' + '$SDWAN.API.URL}') {
		throw 'Please change {' + '$SDWAN.API.URL} macro to the proper value.';
	}

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

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

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

	devices = getHttpData(
		url + 'dataservice/device',
		creds.token,
		creds.cookie
	);

	if (Array.isArray(devices.data)) {
		devices = devices.data;
	}
	else {
		throw 'Failed to parse response received from SD-WAN API. Check debug log for more information.';
	}

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

return JSON.stringify({
	'devices': devices.map(function (device) {
		obj = {
			'name': device['host-name'],
			'token': creds.token,
			'cookie': creds.cookie,
			'id': device['deviceId'],
			'uuid': device['uuid'],
			'type': device['device-type'],
			'model': device['device-model'],
			'ip': device['system-ip'],
			'int_ip': device['local-system-ip'],
			'cert_valid': device['certificate-validity']
		};

		return obj;
	}),
	'error': error_msg.toString()
});