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

function getToken(url, data) {
	var token = null;
	var response = request.post(url, JSON.stringify(data));
	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 {
			token = JSON.parse(response).api_token;
		}
		catch (error) {
			throw 'Failed to get the API token from Pure Storage API. Check debug log for more information.';
		}
	}

	if (token === null || typeof token !== 'string') {
		throw 'Something went wrong while getting the API token. Check debug log for more information.';
	}

	return token;
};

function createSession(url, data) {
	var cookies = [];
	response = request.post(url, JSON.stringify(data));
	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() == 'set-cookie') {
			var entries = headers[key].split(',');
			for (idx in entries) {
				var value = entries[idx].split(';')[0];
				cookies.push(value);
			}
		}
	}

	return cookies;
};

try {

	['url', 'token', 'username', 'password', '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.token == '' & params.username == '' & params.password == '') {
		throw 'To perform authentication, either a token or a username and password must be specified.';
	}

	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');
	if (params.token === '') {
		if (params.username === '' || params.password === '') {
			throw 'Username or password is not specified.';
		}
		params.token = getToken(
			params.url + 'api/' + params.version + '/auth/apitoken',
			{'username': params.username,'password': params.password}
		);
	}
	cookies = createSession(
		params.url + 'api/' + params.version + '/auth/session',
		{'api_token': params.token}
	);

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

return JSON.stringify({
	'cookie': cookies.join('; '),
	'error': error_msg.toString()
});