var base_path = 'cloudsql.googleapis.com/database/sqlserver/transactions/',
	arr = [],
	base_paths = [
		'deadlock_count',
		'lock_wait_count',
		'lock_wait_time'
	];

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 checkParams(params) {
	['project_id', 'time_window', 'database_id', 'token'].forEach(function (field) {
		if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
			throw 'Required param is not set: ' + field + '.';
		}
	});
	if (!params.time_window.match(/^[0-9]+(m|h)$/)) {
		throw 'Incorrect update interval for parameter  time_window. Valid ranges 1m-23h.';
	}
	return params;
}

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

	var response = request.post(url, JSON.stringify(body));

	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 params = checkParams(JSON.parse(value)),
	j_filter = ' | within ' + params.time_window + " | filter database_id = '" + params.database_id + "'" + ' | join',
	url = 'https://monitoring.googleapis.com/v3/projects/' + params.project_id + '/timeSeries:query',
	raw = getHttpData(url, params.token, { query: '{' + base_paths.map(function (path) { return base_path + path; }).join(';') + '}' + j_filter }),
	metrics = getField(raw, 'timeSeriesDescriptor.pointDescriptors'),
	time_series = getField(raw, 'timeSeriesData');

for (t in time_series) {
	data = {
		resource: getField(time_series[t], 'labelValues.3.stringValue'),
		metrics: {}
	};

	for (i in metrics) {
		re = /(^t_\d+\.value(_|\.))/g;
		data['metrics'][getField(metrics[i], 'key').replace(re, '')] = getField(time_series[t], 'pointData.0.values.' + i + '.int64Value');
	}
	arr.push(data);
}
return JSON.stringify(arr);