var Cisco = {
	api_url: '{$CISCO.FTD.API.URL}',
	http_proxy: '{$CISCO.FTD.HTTP_PROXY}',

	getToken: function (params) {
		['access_token'].forEach(function (field) {
			if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
				throw 'Unexpected session token value has been received: ' + field + '.';
			}
		});
		Cisco.params = params;
	},

	request: function (url) {

		var response,
			request = new HttpRequest();

		if (typeof Cisco.http_proxy !== 'undefined' && Cisco.http_proxy !== '') {
			request.setProxy(Cisco.http_proxy);
		}
		if (!Cisco.params.access_token) {
			throw 'Request does not contain access token.';
		}
		request.addHeader('Accept: application/json');
		request.addHeader('Content-Type: application/json');
		request.addHeader('Authorization: Bearer ' + Cisco.params.access_token);

		Zabbix.log(4, '[ Cisco ] request url: ' + url);

		response = request.get(url);

		if (request.getStatus() !== 200) {
			throw 'Request failed with status code ' + request.getStatus() + ': ' + response;
		}

		try {
			return JSON.parse(response);
		}
		catch (error) {
			throw 'Failed to parse response received from API.';
		}
	},

	getMetricsData: function () {
		var data = {};

		endpoints = {
			'cpu': 'monitor/trendingreports/cpu?time_duration=60',
			'memory': 'monitor/trendingreports/memory?time_duration=60',
			'eps': 'monitor/trendingreports/eps?time_duration=60',
			'throughput': 'monitor/trendingreports/throughput?time_duration=60',
			'disk': 'operational/diskusage/default',
			'systeminfo': 'operational/systeminfo/default'
		};

		if (typeof Cisco.api_url === 'string' && !Cisco.api_url.endsWith('/')) {
			Cisco.api_url += '/';
		}

		Object.keys(endpoints).forEach(function (key) {
			data[key] = Cisco.request(Cisco.api_url + endpoints[key]);
		});

		return data;
	}
};

try {
	Cisco.getToken(JSON.parse(value));

	return JSON.stringify(Cisco.getMetricsData());
}
catch (error) {
	error += (String(error).endsWith('.')) ? '' : '.';
	Zabbix.log(3, '[ Cisco ] ERROR: ' + error);

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