
const request_path = '/v3/auth/tokens';

function checkParams(params) {
	['api_url', 'app_cred_id', 'app_cred_secret'].forEach(function (field) {
		if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
			throw 'Required param is not set: ' + field + '.';
		}
	});
	return params;
}

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

	request.addHeader('Content-Type: application/json');

	const request_body = {
		"auth": {
			"identity": {
				"methods": [
					"application_credential"
				],
				"application_credential": {
					"id": app_cred_id,
					"secret": app_cred_secret
				}
			}
		}
	};

	if (params['http_proxy']) {
		request.setProxy(params['http_proxy'])
		Zabbix.log(4, '[ Openstack Nova API ] Using http proxy: ' + params['http_proxy']);
	}

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

	if (request.getStatus() !== 201) {
		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 {'request': request, 'response': response};
}

function parseHttpData(http_data) {
	var token;
	const headers = http_data['request'].getHeaders(true);
	if (typeof headers === "object") {
		if (headers !== null) {
			try {
				token = headers["X-Subject-Token"][0];
			} catch (error) {
				throw 'Failed to parse response received from OpenStack Identity API. Check debug log for more information.';
			}
		} else {
			throw 'Response object is empty. Check debug log for more information.';
		}
	} else {
		throw 'Cannot process response data: received data is not an object. Check debug log for more information.';
	}

	const supported_services = ['nova'];

	var ret = [];
	const data = JSON.parse(http_data['response']);
	if (data['token']['catalog']) {
		const service_catalog = data['token']['catalog'];
	} else {
		throw 'Cannot find service catalog in HTTP response.'
	}

	service_catalog.forEach(function (service) {
		if (supported_services.indexOf(service.name) > -1) {
			service.endpoints.forEach(function (endpoint) {
				if (endpoint.interface === 'public') {
					ret.push({
						'service_name': service.name[0].toUpperCase() + service.name.slice(1),
						'service_url': endpoint.url,
						'token': token
					});
				}
			})
		}
	});

	return JSON.stringify(ret);
}

const params = checkParams(JSON.parse(value)),
	url = params.api_url,
	auth_cred_id = params.app_cred_id,
	auth_cred_secret = params.app_cred_secret;

const httpData = getHttpData(url + request_path, params, auth_cred_id, auth_cred_secret);
return parseHttpData(httpData);