var Nutanix = {
	params: {},

	setParams: function (requiredParams, allParams) {
		requiredParams.forEach(function (field) {
			if (typeof allParams !== 'object' || typeof allParams[field] === 'undefined' || allParams[field] === '') {
				throw 'Required param is not set: ' + field + '.';
			}
		});

		Nutanix.params = params;
	},

	request: function (url) {

		var request = new HttpRequest();

		if (typeof Nutanix.params.proxy !== 'undefined' && Nutanix.params.proxy !== '') {
			request.setProxy(Nutanix.params.proxy);
		}

		request.setHttpAuth(HTTPAUTH_BASIC, Nutanix.params.username, Nutanix.params.password);

		Zabbix.log(4, '[ Nutanix ] Sending request: ' + url);

		const response = request.get(url);

		Zabbix.log(4, '[ Nutanix ] Received response with status code ' + request.getStatus() + ': ' + response);

		if (request.getStatus() < 200 || request.getStatus() >= 300) {
			throw 'Request failed with status code ' + request.getStatus() + ': ' + response;
		}

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

		return response;
	},

	deduplicateAlerts: function (full_data) {
		const severity_mapping = [
			'kinfo',
			'kwarning',
			'kcritical'
		]

		var output_data = {};
		for (var entity in full_data.entities) {
	
			if (Nutanix.params.api_method === 'clusters') {
				if (result.entities[entity].node_uuid.split('-').length == 5) continue;
			}

			var severity = severity_mapping.indexOf(full_data.entities[entity].severity.toLowerCase()),
				message = full_data.entities[entity].message,
				title = full_data.entities[entity].alert_title;
	
			full_data.entities[entity].context_types.forEach(function(context, index) {
				message = message.replace('{' + context + '}', full_data.entities[entity].context_values[index]);
				title = title.replace('{' + context + '}', full_data.entities[entity].context_values[index]);
			});
	
			key = md5(title + message);
			if (key in output_data) {
				if (full_data.entities[entity].created_time_stamp_in_usecs > output_data[key].created) {
					output_data[key].created = full_data.entities[entity].created_time_stamp_in_usecs;
					output_data[key].severity = severity !== -1 ? severity : 3;
					output_data[key].state = full_data.entities[entity].resolved ? 0 : 1;
					output_data[key].message = full_data.entities[entity].detailed_message != '' ? full_data.entities[entity].detailed_message : message;
					output_data[key].last_id = full_data.entities[entity].id;
				}
				output_data[key].count += 1;
			} else {
				output_data[key] = {
					"name": title + ' - ' + message,
					"title": title != '' ? title : message,
					"created": full_data.entities[entity].created_time_stamp_in_usecs,
					"severity": severity !== -1 ? severity : 3,
					"state": full_data.entities[entity].resolved ? 0 : 1,
					"message": full_data.entities[entity].detailed_message != '' ? full_data.entities[entity].detailed_message : message,
					"last_id": full_data.entities[entity].id,
					"count": 1
				}
			}
		}

		return output_data;
	},

	cleanUnsupported: function (full_stat) {
		var output_stat = {};
		for (var element in full_stat) {
			if (full_stat[element] !== '-1') {
				output_stat[element] = full_stat[element];
			}
		};
		
		return output_stat;
	}
};

try {
	const params = JSON.parse(value);
	Nutanix.setParams(['endpoint_host', 'endpoint_port', 'username', 'password', 'auth_type', 'api_method', 'target_uuid'], params);

	const url = 'https://' + Nutanix.params.endpoint_host + ':' + Nutanix.params.endpoint_port + '/PrismGateway/services/rest/v2.0/' + Nutanix.params.api_method + '/' + Nutanix.params.target_uuid + '/alerts',
		result = Nutanix.request(url);

	return JSON.stringify(Nutanix.deduplicateAlerts(result));
}
catch (error) {
	error += (String(error).endsWith('.')) ? '' : '.';
	Zabbix.log(4, '[ Nutanix ] ERROR: ' + error);

	return JSON.stringify({ 'error': error });
}