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

function authenticate(url) {
	var payload = 'j_username=' + encodeURIComponent(params.username)
		+ '&j_password=' + encodeURIComponent(params.password);
	request.addHeader('Content-Type', 'application/x-www-form-urlencoded');
	response = request.post(url, payload);
	Zabbix.log(4, '[ SD-WAN 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 && response != "") {
		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);
			}
		}
	}
};

function getToken(url) {
	response = request.get(url);
	Zabbix.log(4, '[ SD-WAN API ] [ ' + url + ' ] Received response with status code ' + request.getStatus() + ': ' + response);

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

	var headers = request.getHeaders();
	for (key in headers) {
		if (key.toLowerCase() == 'content-type' && headers[key] != 'application/json') {
			throw 'Something went wrong while getting the authentication token. Check debug log for more information.';
		}
	}

	return response;
};

try {

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

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

	if (!params.url.endsWith('/')) {
		params.url += '/';
	}

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

	authenticate(params.url + 'j_security_check');
	token = getToken(params.url + 'dataservice/client/token');

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

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