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

function getHttpData(url) {
	request.addHeader('Accept: application/json');
	request.addHeader('Authorization: Bearer ' + params.token);
	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 resource_list = getHttpData(
		api_url + '/api/v2/monitor/system/resource/usage?interval=1-min'
	);

	var disk_info = getHttpData(
		api_url + '/api/v2/monitor/log/current-disk-usage'
	);

	if (typeof resource_list.results !== 'undefined' && typeof resource_list.results === 'object') {
		Object.keys(resource_list.results).forEach(function (key) {
			var resource = resource_list.results[key];
			if (resource.length > 0) {
				result.data[key] = resource[0].current;
			}
		});
	}
	else {
		throw 'Failed to parse response received from FortiGate API. Check debug log for more information.';
	}

	Object.keys(disk_info.results).forEach(function (key) {
		result.data['disk_' + key.split('_')[0]] = disk_info.results[key];
	});
} 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);