var Ribbon = {
	params: {},
	request: new HttpRequest(),

	setParams: function (params) {
		['url', 'username', 'password'].forEach(function (field) {
			if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
				throw 'Required param is not set: ' + field + '.';
			}
		});

		Ribbon.params = params;

		if (typeof Ribbon.params.url === 'string') {
			if (Ribbon.params.url.endsWith('/')) {
				Ribbon.params.url = Ribbon.params.url.slice(0,-1);
			}
		}

	},

	getRequest: function (url) {
		var response;

		if (typeof Ribbon.params.proxy !== 'undefined' && Ribbon.params.proxy !== '') {
			Ribbon.request.setProxy(Ribbon.params.proxy);
		}

		Zabbix.log(4, '[ Ribbon SBC Edge ] Sending request: ' + Ribbon.params.url  + url);

		response = Ribbon.request.get(Ribbon.params.url + url);

		Zabbix.log(4, '[ Ribbon SBC Edge ] Received response with status code ' + Ribbon.request.getStatus() + ': ' + response);

		if (Ribbon.request.getStatus() < 200 || Ribbon.request.getStatus() >= 300) {
			throw 'Cannot connect to Ribbon SBC. Check debug log for more information.';
		}

		try {
			response = JSON.parse(XML.toJson(response));
		}
		catch (error) {
			throw 'Failed to parse response received from Ribbon SBC API. Check debug log for more information.';
		}

		return response;
	},

	getField: function (data, path) {
		const steps = path.split('.');

		for (var i = 0; i < steps.length; i++) {
			var step = steps[i];

			if (typeof data !== 'object' || typeof data[step] === 'undefined') {
				throw 'Required field was not found: ' + path;
			}
			data = data[step];
		}

		return data;
	},

	login: function () {
		var response = "",
			cookies = "",
			payload = 'Username=' + encodeURIComponent(Ribbon.params.username) + '&Password=' + encodeURIComponent(Ribbon.params.password);

		Ribbon.request.addHeader('Content-Type', 'application/x-www-form-urlencoded');
		response = Ribbon.request.post(Ribbon.params.url + '/rest/login', payload);

		var headers = Ribbon.request.getHeaders();
		for (var key in headers) {
			if (key.toLowerCase() == 'set-cookie') {
				cookies = headers[key];
			}
		}

		Ribbon.request.addHeader('Cookie', cookies);
	},

	logout: function () {
		var response = Ribbon.request.post(Ribbon.params.url + '/rest/logout');

		return JSON.parse(XML.toJson(response));
	}
};

try {
	var result = {};

	Ribbon.setParams(JSON.parse(value));
	Ribbon.login();

	var fan_list = Ribbon.getField(Ribbon.getRequest("/rest/fan"), 'root.fan_list'),
		count = Ribbon.getField(fan_list, '@count');

	if (count !== '0') {
		var fans = Ribbon.getField(fan_list, 'fan_pk');

		if (!Array.isArray(fans)) {
			fans = [fans];
		}

		for (var fan in fans) {
			var id = Ribbon.getField(fans[fan], '@id');
			result[id] = Ribbon.getField(Ribbon.getRequest("/rest/fan/" + id), 'root.fan');
		}
	}

	Ribbon.logout();

	return JSON.stringify(result);
}
catch (error) {
	Zabbix.log(3, '[ Ribbon SBC Edge ] Fan ERROR: ' + error);
	error_msg = 'Failed to get fans data from API:' + error;

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