var Nomad = {
	setParams: function (params) {
		['api_endpoint'].forEach(function (field) {
			if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
				throw 'Required param is not set: "' + field + '".';
			}
		});

		Nomad.params = params;
		if (typeof Nomad.params.api_endpoint === 'string' && !Nomad.params.api_endpoint.endsWith('/')) {
			Nomad.params.api_endpoint += '/';
		}
	},

	request: function (query) {
		var response,
			request = new HttpRequest(),
			url = Nomad.params.api_endpoint + query;

		request.addHeader('Content-Type: application/json');
		request.addHeader('X-Nomad-Token: ' + Nomad.params.token);
		if (Nomad.params.http_proxy) {
			request.setProxy(Nomad.params.http_proxy)
			Zabbix.log(4, '[ Nomad ] Using http proxy: ' + Nomad.params.http_proxy);
		}

		Zabbix.log(4, '[ Nomad ] Sending request: ' + url);
		response = request.get(url);

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

		if (response !== null) {
			try {
				response = JSON.parse(response);
			}
			catch (error) {
				throw 'Failed to parse response received from Nomad agent API.';
			}
		}

		return {
			status: request.getStatus(),
			response: response
		};
	},

	getField: function (data, path) {
		var steps = path.split('.');
		for (var i = 0; i < steps.length; i++) {
			var step = steps[i];
			if (typeof data !== 'object' || typeof data[step] === 'undefined') {
				throw 'Required field was not found: ' + path;
			}

			data = data[step];
		}

		return data;
	},

	getIds: function () {
		var result = this.request('v1/operator/raft/configuration');

		if (typeof result.response !== 'object' || result.status != 200) {
			throw 'Cannot get servers list from Nomad agent API.';
		}

		return this.getField(result, 'response.Servers')
			.map(function (srv) {
				return srv['ID'];
			});
	},

	getServers: function () {
		var ids = this.getIds();
		result = Nomad.request('v1/agent/members');

		if (typeof result.response !== 'object' || result.status != 200) {
			throw 'Cannot get servers list from Nomad agent API.';
		}

		return this.getField(result,'response.Members').filter(function (s) {
			return ids.indexOf(s.Tags.id) >= 0;
		});

	},
};

try {
	Nomad.setParams(JSON.parse(value));

	var servers = Nomad.getServers();

	return JSON.stringify(servers);

}
catch (error) {
	error += ((String(error).endsWith('.')) ? '' : '.');
	Zabbix.log(3, '[ Nomad ] ERROR: ' + error);

	return JSON.stringify({ error: error + ' Check debug log for more information.' });
}