var YugabyteDB = {
	params: {},
	metrics: {},
	error_msg: '',

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

		YugabyteDB.params = params;
	},


	request: function (url, data) {
		if (typeof data === 'undefined' || data === null) {
			data = '';
		}

		var response, request = new HttpRequest();
		if (typeof YugabyteDB.params.proxy !== 'undefined' && YugabyteDB.params.proxy !== '') {
			request.setProxy(YugabyteDB.params.proxy);
		}
		if (YugabyteDB.params.token) {
			request.addHeader('Accept: application/json');
			request.addHeader('Authorization: Bearer ' + YugabyteDB.params.token);
		}

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

		response = request.get(url);

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

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

		try {
			return JSON.parse(response);
		}
		catch (error) {
			throw 'Failed to parse response received from API:' + error;
		}
	},


	get_last_values: function (values) {
		var max_timestamp = 0;
		var last_value = 0;
		for (e in values) {
			if (values[e][0] > max_timestamp) {
				max_timestamp = values[e][0];
				last_value = values[e][1];
			};
		};
		return last_value;
	},


	get_start_time: function() {
		return Math.floor(Date.now() / 1000 - 300);
	}

};

metrics = [
	"CPU_USAGE",
	"DISK_USAGE_GB",
	"PROVISIONED_DISK_SPACE_GB",
	"READ_OPS_PER_SEC",
	"WRITE_OPS_PER_SEC",
	"AVERAGE_READ_LATENCY_MS",
	"AVERAGE_WRITE_LATENCY_MS",
	"YSQL_CONNECTION_LIMIT",
	"AVERAGE_YSQL_CONNECTION_COUNT",
	"NODE_CLOCK_SKEW",
	"DISK_BYTES_READ_MB_PER_SEC",
	"DISK_BYTES_WRITTEN_MB_PER_SEC",
	"FOLLOWER_LAG_MS",
	"MEMORY_TOTAL_GB",
	"MEMORY_USAGE_GB",
	"NETWORK_RECEIVE_BYTES_MB_PER_SEC",
	"NETWORK_TRANSMIT_BYTES_MB_PER_SEC",
	"NETWORK_RECEIVE_ERRORS_PER_SEC",
	"NETWORK_TRANSMIT_ERRORS_PER_SEC",
	"MASTER_UP_STATUS",
	"TSERVER_UP_STATUS",
	"YSQL_MAX_CONNECTION_COUNT"
]

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

	var size = 6

	for (var i = 0; i < Math.ceil(metrics.length/size); i++)  {
		var values = YugabyteDB.request(
			'https://cloud.yugabyte.com/api/public/v1/accounts/' + YugabyteDB.params.account_id + '/projects/' + YugabyteDB.params.project_id + '/clusters/' + YugabyteDB.params.cluster_id + '/metrics?metrics=' + metrics.slice((i * size), (i * size) + size).join('%2C') + '&start_time=' + YugabyteDB.get_start_time()
		);

		values.data.forEach(function (e) {
			YugabyteDB.metrics[e.name] = YugabyteDB.get_last_values(e.values)
		});
	};
}
catch (error) {
	Zabbix.log(3, '[ YugabyteDB ] ERROR: ' + error);
	error_msg = 'Failed to get data from API:' + error;
}

return JSON.stringify({'metrics': YugabyteDB.metrics, 'error': YugabyteDB.error_msg});