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

function getHttpData(url) {
	response = request.get(url);
	Zabbix.log(4, '[ FortiGate ] [ ' + url + ' ] Received response with status code ' + request.getStatus() + ': ' + response);

	if (request.getStatus() !== 200) {
		throw 'Failed to receive data: invalid response status code. Check debug log for more information.';
	}

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

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

	if ((typeof response.status !== 'undefined' && response.status != 'success') || typeof response.results === 'undefined') {
		var uri = '/' + response.path + '/' + response.name + ((typeof response.action !== 'undefined') ? '?action=' + response.action : "");
		throw 'Failed to parse response received from ' + uri + '. Check debug log for more information.';
	}

	return response;
};

try {
	['scheme', 'api.token', 'api.fqdn', 'api.port'].forEach(function (field) {
		var macro = '{$FGATE.' + field.toUpperCase() + '}';
		var key = field.split('.').pop();
		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 (typeof params.http_proxy !== 'undefined' && params.http_proxy !== '{' + '$FGATE.HTTP.PROXY}' && params.http_proxy !== '') {
		request.setProxy(params.http_proxy);
	}

	api_url = params.scheme + '://' + params.fqdn + ':' + params.port;

	var sdwan_member_data = getHttpData(
		api_url + '/api/v2/monitor/virtual-wan/members?access_token=' + encodeURIComponent(params.token)
	);

	var sdwan_health_data = getHttpData(
		api_url + '/api/v2/monitor/virtual-wan/health-check?access_token=' + encodeURIComponent(params.token)
	);

	var sdwan_list = getHttpData(
		api_url + '/api/v2/cmdb/system/sdwan?access_token=' + encodeURIComponent(params.token)
	);

	sdwan_list.results['health-check'].forEach(function (item) {
		health_checks[item.q_origin_key] = item.members.length;
		item.members.forEach(function (m) {
			health_members.push({
				'member_id': m.q_origin_key,
				'health_id': item.q_origin_key,
				'health_name': item.name,
			});
		});
	});

	sdwan_list.results.members.forEach(function (item) {
		members[item.q_origin_key] = item;
	});

	result.data = {
		'member_lld': sdwan_list.results.members.filter(function (v) {
			if (v.interface.length > 0) {
				return v;
			}
		}).map(function (v) {
			if (typeof v.interface !== 'undefined' && typeof sdwan_member_data.results[v.interface] !== 'undefined') {
				Object.assign(v, sdwan_member_data.results[v.interface]);
			}
			return v;
		}),
		'health_lld': health_members.map(function (m) {
			var item = {};
			if (typeof members[String(m.member_id)] !== 'undefined') {
				['interface', 'status'].forEach(function (k) {
					item[k] = members[String(m.member_id)][k];
				});
				Object.assign(item, m);
			};
			return item;
		}).filter(function (v) {
			if (v.interface.length > 0) {
				return v;
			}
		}),
		'health_data': sdwan_list.results['health-check'].filter(function (v) {
			if (typeof health_checks[String(v.q_origin_key)] !== 'undefined' && health_checks[String(v.q_origin_key)] > 0) {
				return v;
			}
		}).map(function (v) {
			delete v.members;
			if (typeof v.name !== 'undefined' && typeof sdwan_health_data.results[v.name] !== 'undefined') {
				Object.assign(v, sdwan_health_data.results[v.name]);
			}
			return v;
		})
	}
} catch (error) {
	error_msg = error.toString();
	error_msg += error_msg.endsWith('.') ? '' : '.';
	Zabbix.log(3, '[ FortiGate ] ERROR: ' + error_msg);
};

result.error = error_msg;

return JSON.stringify(result);