var params = JSON.parse(value),
	request = new HttpRequest(),
	token = '',
	error_msg = '';

function login(url) {
	var token = '';
	response = request.post(url);
	Zabbix.log(4, '[ Pure Storage API ] [ ' + url + ' ] Received response with status code ' + request.getStatus() + ': ' + response);

	if (request.getStatus() !== 200) {
		throw 'Failed to receive data: invalid response status code.';
	}

	if (response !== null) {
		try {
			username = JSON.parse(response).username;
		}
		catch (error) {
			throw 'Failed to parse response received from Pure Storage API. Check debug log for more information.';
		}
	} else {
		throw 'Authentication failed.';
	}

	var headers = request.getHeaders();
	for (key in headers) {
		if (key.toLowerCase() == 'x-auth-token') {
			token = headers[key];
		}
	}

	return token;
};

try {

	['url', 'token', 'version'].forEach(function (field) {
		var macro = '{$PURE.FLASHARRAY.API.' + field.toUpperCase() + '}';
		if (typeof params[field] === 'undefined' || params[field] === macro) {
			throw 'Please set \\'' + field + '\\' script input parameter to the proper ' + macro + ' macro value.';
		}
	});
	['url', 'version'].forEach(function (field) {
		if (typeof params[field] == '') {
			throw 'Please set \\'' + field + '\\' script input parameter to the proper value.';
		}
	});

	if (params.url.indexOf('http://') === -1 && params.url.indexOf('https://') === -1) {
		params.url = 'https://' + params.url + (!params.url.endsWith('/') ? '/' : '');;
	}

	if (typeof params.http_proxy !== 'undefined' && params.http_proxy !== '{' + '$PURE.FLASHARRAY.HTTP_PROXY}' && params.http_proxy !== '') {
		request.setProxy(params.http_proxy);
	}

	request.addHeader('Accept: application/json');
	request.addHeader('Content-Type: application/json');
	request.addHeader('api-token: ' + params.token);
	token = login(
		params.url + 'api/' + params.version + '/login'
	);

} catch (err) {
	error_msg = err;
};

return JSON.stringify({
	'token': token,
	'error': error_msg.toString()
});