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

	setParams: function (params) {
		['account_id', 'project_id', 'token'].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_keyspace: function (tables) {
		var table_info = {};
		var result = [];
		for (var table in tables['data']) {
			var table_name = tables['data'][table]['keyspace'];
			if (typeof table_info[table_name] !== 'undefined') {
				table_info[table_name]['size_bytes'] += tables['data'][table]['size_bytes']
				table_info[table_name]['wal_size_bytes'] += tables['data'][table]['wal_size_bytes']
			}
			else {
				table_info[table_name] = {
					'keyspace_name': table_name,
					'size_bytes': tables['data'][table]['size_bytes'],
					'wal_size_bytes': tables['data'][table]['wal_size_bytes'],
					'type': tables['data'][table]['type']}
			}
		}
		for (keyspace in table_info) {
			result.push(table_info[keyspace])
		}
		return result;
	}

};

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

	var tables = YugabyteDB.request(
		'https://cloud.yugabyte.com/api/public/v1/accounts/' + YugabyteDB.params.account_id + '/projects/' + YugabyteDB.params.project_id + '/clusters/' + YugabyteDB.params.cluster_id + '/tables'
	)
	
	YugabyteDB.keyspaces = YugabyteDB.get_keyspace(tables);
}
catch (error) {
	Zabbix.log(3, '[ YugabyteDB ] ERROR: ' + error);
	error_msg = 'Failed to get data from API:' + error;
}

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