
const request_path = '/os-simple-tenant-usage';

function checkParams(params) {
	['api_url', 'api_token', 'period'].forEach(function (field) {
		if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
			throw 'Required param is not set: ' + field + '.';
		}
		if (field === 'period') {
			const supported_values = ['y', 'm', 'w', 'd']
			if (supported_values.indexOf(params[field]) === -1) {
				throw 'Tenant period not correctly set. Expected one of "y", "m", "w", "d"; received: ' + field + '.';
			}
		}
	});
	return params;
}

function buildUrl(url, period) {
	const current_date = new Date();
	var datetime_formatted = ''
	switch (period) {
		case 'y':
			datetime_formatted =
				current_date.getFullYear() + '-' +
				'1-' +
				'1T' +
				'00:00:00'
			break;
		case 'm':
			datetime_formatted =
			current_date.getFullYear() + '-' +
				(current_date.getMonth() + 1) + '-' +
			'1T' +
			'00:00:00'
			break;
		case 'w':
			const first_date_of_week = current_date.getDate() - current_date.getDay() + 1
			datetime_formatted =
				current_date.getFullYear() + '-' +
				(current_date.getMonth() + 1) + '-' +
				first_date_of_week + 'T' +
				'00:00:00'
			break;
		case 'd':
			datetime_formatted =
				current_date.getFullYear() + '-' +
				(current_date.getMonth() + 1) + '-' +
				current_date.getDate() + 'T' +
				'00:00:00'
			break;
	}

	return url + request_path + '?' +
		'start=' + encodeURIComponent(datetime_formatted)
}

function getHttpData(url, params, api_token) {
	const request = new HttpRequest();

	request.addHeader('Content-Type: application/json');
	request.addHeader('X-Auth-Token: ' + api_token);
	if (params['http_proxy']) {
		request.setProxy(params['http_proxy'])
		Zabbix.log(4, '[ Openstack Nova API ] Using http proxy: ' + params['http_proxy']);
	}

	const response = request.get(url, JSON.stringify(params));
	Zabbix.log(4, '[ Openstack Nova API ] [ ' + url + ' ] Received response with status code ' + request.getStatus() + ': ' + response);

	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 ( ' + request.getStatus() + ' ). Check debug log for more information.';
		}
	}

	return response;
}

const params = checkParams(JSON.parse(value)),
	url = params.api_url,
	token = params.api_token,
	period = params.period;

return getHttpData(buildUrl(url, period), params, token);