var Vcenter = {
	 params: {},
	 vmware_api_session_id: '',
	 health_status: '',
	 error_msg: '',

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

		  if (params['url'].endsWith('/')) {
			   params['url'] = params['url'].slice(0,-1);
		  }
		  params['url'] = params['url'].replace('/sdk','');

		  Vcenter.params = params;
	 },

	 isGtOrEqVersion: function (first_version, second_version) {
		  var first = first_version.split('.').map(Number),
			  second = second_version.split('.').map(Number);

		  if (first.length > second.length) {
			  const max_componens_length = first.length
		  }
		  else {
			  const max_componens_length = second.length
		  }

		  var num_components = first.length;
		  while (num_components < max_componens_length) {
			  first.push(0);
			  num_components = num_components +1;
		  }

		  var num_components = second.length;
		  while (num_components < max_componens_length) {
			  second.push(0);
			  num_components = num_components +1;
		  }

		  if (first[0] > second[0] ||
			  (first[0] === second[0] && first[1] > second[1]) ||
			  (first[0] === second[0] && first[1] === second[1] && first[2] >= second[2])) {
			  return true;
		  }

		  return false;
	  },

	 login: function () {
		  var response, request = new HttpRequest();
		  request.setHttpAuth(HTTPAUTH_BASIC, Vcenter.params.username, Vcenter.params.password);
		  request.addHeader('Accept: application/json');
		  request.addHeader('Content-Type: application/json');

		  response = request.post(Vcenter.params.url + '/api/session', '');
		  if (request.getStatus() >= 200 && request.getStatus() < 300 && (!JSON.parse(response).error)) {
			   Vcenter.vmware_api_session_id = Vcenter.removeQuotes(response);
			   return true;
		  }

		  response = request.post(Vcenter.params.url + '/rest/com/vmware/cis/session', '');
		  if (request.getStatus() >= 200 && request.getStatus() < 300) {
			   Vcenter.vmware_api_session_id = JSON.parse(response).value;
			   return true;
		  }

		  return false;
	 },

	 logout: function () {
		  path = '/rest/com/vmware/cis/session';
		  if (Vcenter.vmware_api_version && Vcenter.isGtOrEqVersion(Vcenter.vmware_api_version, '7.0.2')) {
			   path = '/api/session';
		  }

		  Vcenter.request(Vcenter.params.url + path, 'delete');
	 },

	 get_version: function () {
		  path = '/rest/appliance/system/version';

		  try {
			   Vcenter.vmware_api_version = Vcenter.request(Vcenter.params.url + path, 'get').version;
			   return true;
		  }
		  catch (error) {
			   return false;
		  }
	 },

	 removeQuotes: function (str){
		  if (str.startsWith('"') && str.endsWith('"')) {
			  return str.slice(1, -1);
		  }

		  return str;
	 },

	 getHealthStatus: function () {
		  path = '/api/appliance/health/system';
		  if (!Vcenter.isGtOrEqVersion(Vcenter.vmware_api_version, '7.0.2')) {
			   path = '/rest/appliance/health/system';
		  }

		  result = Vcenter.removeQuotes(Vcenter.request(Vcenter.params.url + path, 'get'));

		  const idx = [
			   'green',
			   'yellow',
			   'orange',
			   'red',
			   'gray'
			   ].indexOf(result.toLowerCase());
		  Vcenter.health_status = idx !== -1 ? idx : 5;
	 },

	 request: function (url, method) {
		  var response, request = new HttpRequest();

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

		  request.setHttpAuth(HTTPAUTH_NONE);
		  request.addHeader("Cookie: vmware-api-session-id=" + Vcenter.vmware_api_session_id);

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

		  switch (method) {
			   case 'get':
				   response = request.get(url);
				   break;

			   case 'post':
				   response = request.post(url);
				   break;

			   case 'delete':
					response = request.delete(url);
					break;

			   default:
				   throw 'Unsupported HTTP request method: ' + method;
		  }

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

		  if (request.getStatus() < 200 || request.getStatus() >= 300) {
			   throw 'Cannot connect to VMware vCenter. Check debug log for more information.';
		  }

		  if (method !== 'delete' && JSON.parse(response).value) {
			   return JSON.parse(response).value;
		  }
		  else {
			   return response;
		  }
	 }
};

try {
	 Vcenter.setParams(JSON.parse(value));
	 
	 if (Vcenter.login() && Vcenter.get_version() && Vcenter.isGtOrEqVersion(Vcenter.vmware_api_version, '6.5.0')) {
		  Vcenter.getHealthStatus();
	 }
	 else {
		  Vcenter.health_status = 6;
	 }

	 if (Vcenter.vmware_api_session_id) {
		  Vcenter.logout();
	 }
}
catch (error) {
	 Zabbix.log(3, '[ VMware vCenter ] ERROR: ' + error);
	 Vcenter.error_msg = 'Failed to get data from API:' + error;
}

return JSON.stringify({'health': Vcenter.health_status, 'error': Vcenter.error_msg});