var token = value;

function checkMacro(macro) {
	if (!macro || macro.match(/^\{\$.*\}$/)) {
		throw 'The GCP project id is not defined. Please, set the value for the \{$GCP.PROJECT.ID\} macro.';
	}
	return macro;
}

function getField(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 "' + path + '" is not present in data received.'
		}
		data = data[step];
	}
	return data;
}

function getHttpData(url, token) {
	var request = new HttpRequest(),
		proxy = '{$GCP.PROXY}';
	if (proxy !== '{' + '$GCP.PROXY}' && proxy !== '') {
		request.setProxy(proxy);
	};
	request.addHeader('Authorization: Bearer ' + token);
	request.addHeader('Content-Type: application/json');

	var response = request.get(url);

	Zabbix.log(4, '[ GCP API ] [ ' + url + ' ] 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 GCP API. Check debug log for more information.';
		}
	}

	if (typeof response !== 'object' || response === null) {
		throw 'Cannot process response data: received data is not an object. Check debug log for more information.';
	}

	if (request.getStatus() !== 200) {
		if (typeof (response.error && response.error.message) !== 'undefined') {
			throw response.error.message;
		}
		else {
			throw 'Failed to receive data: invalid response status code. Check debug log for more information.';
		}
	}

	if (typeof response.quotas !== 'undefined') {
		return response;
	} else {
		throw 'No quotas array in API response';
	}
};
var project = checkMacro('{$GCP.PROJECT.ID}'),
	qts_raw = getHttpData('https://www.googleapis.com/compute/v1/projects/' + project, token),
	qts_lst = getField(qts_raw, 'quotas').map(function (qt) {
		obj = {
			metric: getField(qt, 'metric'),
			limit: getField(qt, 'limit'),
			usage: getField(qt, 'usage'),
			p_used: (qt.usage / qt.limit) * 100
		};
		return obj;
	});

return JSON.stringify(qts_lst);