var params = JSON.parse(value),
	request = new HttpRequest(),
	result = {"data": {}, "error": ""},
	api_url = "",
	policies = {},
	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 firewall_data = getHttpData(
		api_url + '/api/v2/monitor/firewall/policy?access_token=' + encodeURIComponent(params.token)
	);

	var firewall_list = getHttpData(
		api_url + '/api/v2/cmdb/firewall/policy?access_token=' + encodeURIComponent(params.token)
	);

	firewall_list.results.forEach(function (v) {
		var item = {};
		['q_origin_key', 'status', 'name', 'uuid', 'action', 'ip-version-type', 'label'].forEach(function (k) {
			item[k] = v[k];
		});
		policies[v.policyid] = item;
	});

	result.data = firewall_data.results.map(function (v) {
		if (typeof v.policyid !== 'undefined' && typeof policies[String(v.policyid)] !== 'undefined') {
			Object.assign(v, policies[String(v.policyid)]);
		}
		return v;
	}).filter(function (v) {
		if (typeof v.name !== 'undefined') {
			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);