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 getFieldBool(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') {
			return false;
		}
		data = data[step];
	}
	return true;
}


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.';
		}
	}
	return response;
};

var project = '{$GCP.PROJECT.ID}';

if (!project || project === '{' + '$GCP.PROJECT.ID}') {
	throw 'Error. Set the \{$GCP.PROJECT.ID\} macro value.';
}

var result = getHttpData('https://compute.googleapis.com/compute/v1/projects/' + project + '/aggregated/instances', token),
	vms_raw = getField(result, 'items'),
	keys = Object.keys(vms_raw),
	arr = [];

for (var i in keys) {
	if (typeof vms_raw[keys[i]].instances !== 'undefined') {
		var vm_prop = vms_raw[keys[i]].instances.map(function setProp(inst) {
			obj = {
				id: getField(inst, 'id'),
				name: getField(inst, 'name'),
				token: value,
				zone: keys[i].replace(/zones\//, ''),
				m_type: getField(inst, 'machineType').replace(/.*machineTypes\//g, ''),
				state: getField(inst, 'status'),
				project_id: '{$GCP.PROJECT.ID}',
				ip: getField(inst, 'networkInterfaces.0.networkIP'),
				integrity: getFieldBool(inst, 'shieldedInstanceConfig.enableIntegrityMonitoring') ? inst.shieldedInstanceConfig.enableIntegrityMonitoring : false
			};

			obj.ext_ip = getFieldBool(inst, 'networkInterfaces.0.accessConfigs.0.natIP') ? inst.networkInterfaces[0].accessConfigs[0].natIP : '0.0.0.0';
			obj.i_type = getFieldBool(inst, 'labels.container-vm') ? 'container-optimized' : 'regular';
			return obj;
		});
		arr = arr.concat(vm_prop);
	}
}
return JSON.stringify(arr);