var params = JSON.parse(value),
	request = new HttpRequest(),
	result = {"data": {}, "lld": [], "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;
};

function capitalize(word, idx) {
	return upAcronymCase(word.charAt(idx).toUpperCase() + word.slice(idx+1));
}

function upAcronymCase(word) {
	if (word.length < 4) {
		return word.toUpperCase()
	}
	return word;
}

function prepareServiceName(key) {
	var result = [];
	key.split('_').forEach(function (w) {
		var forti_idx = w.indexOf('forti');
		w = upAcronymCase(w);
		if (forti_idx !== -1)
			w = 'Forti' + capitalize(w, forti_idx + 5);
		else
			w = capitalize(w, 0)
		result.push(w);
	});

	return result.join(' ');
};

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.';
		}
	});

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

	if (typeof params.http_proxy !== 'undefined' && params.http_proxy !== '{' + '$FGATE.HTTP.PROXY}' && params.http_proxy !== '') {
		request.setProxy(params.http_proxy);
	}

	var licence_list = getHttpData(
		api_url + '/api/v2/monitor/license/status'
	);

	result.data = licence_list.results;
	Object.keys(licence_list.results).forEach(function (key) {
		var resource = licence_list.results[key];
		if (typeof resource.status !== 'undefined' && typeof resource.type !== 'undefined') {
			result.lld.push({
				"key": key,
				"name": prepareServiceName(key),
				"status": resource.status,
				"type": resource.type,
			});
		}
	});
} 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);