var params = JSON.parse(value);

var request = new HttpRequest();

request.addHeader('X-Cisco-Meraki-API-Key:' + params.token);
request.addHeader('User-Agent: ZabbixServer/1.1 Zabbix');

var response,
	error_msg = '',
	vpnStats = [],
	vpnStatuses = [],
	result = [];

function isFloat(n) {
	n = parseFloat(n);
	return Number(n) === n && n % 1 !== 0;
};

function checkNumber(string) {
	if (typeof string !== "string" || isNaN(string) || isFloat(string)) {
		throw 'Incorrect "timespan" parameter given: ' + string + ' Must be an unsigned number';
	}
	return string;
};

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

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

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

	if (typeof (response) !== 'object' || response === null) {
		throw 'Cannot process response data: received data is not an object.';
	}

	return response;
};

try {

	if (params.token === '{' + '$MERAKI.TOKEN}') {
		throw 'Please change {' + '$MERAKI.TOKEN} macro to the proper 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.httpproxy !== 'undefined' && params.httpproxy !== '') {
		request.setProxy(params.httpproxy);
	}

	timespan = checkNumber('{$MERAKI.VPN.STATS.TIMESPAN}');

	if (timespan > 86400 || timespan < 1) {
		throw 'Incorrect "timespan" parameter given: ' + timespan + ' Must be between 1 and 86400 seconds.';
	}

	vpnStats = getHttpData(params.url + 'organizations/' + encodeURIComponent(params.organizationId) + '/appliance/vpn/stats?timespan=' + timespan);

	for (i in vpnStats) {
		if (typeof vpnStats[i].merakiVpnPeers !== 'undefined' && Array.isArray(vpnStats[i].merakiVpnPeers)) {
			for (u in vpnStats[i].merakiVpnPeers) {
				if (typeof vpnStats[i].merakiVpnPeers[u].latencySummaries !== 'undefined' && Array.isArray(vpnStats[i].merakiVpnPeers[u].latencySummaries)) {
					vpn_stats = vpnStats[i].merakiVpnPeers[u].latencySummaries.map(function (x) {

						lps = vpnStats[i].merakiVpnPeers[u].lossPercentageSummaries.filter(function (y) { return y.senderUplink == x.senderUplink && y.receiverUplink == x.receiverUplink; });
						js = vpnStats[i].merakiVpnPeers[u].jitterSummaries.filter(function (y) { return y.senderUplink == x.senderUplink && y.receiverUplink == x.receiverUplink; });
						ms = vpnStats[i].merakiVpnPeers[u].mosSummaries.filter(function (y) { return y.senderUplink == x.senderUplink && y.receiverUplink == x.receiverUplink; });
						Object.assign(x, lps[0], js[0], ms[0]);

						if ('networkId' in vpnStats[i]) {
							x.networkId = vpnStats[i].networkId;
						}
						if ('networkName' in vpnStats[i]) {
							x.networkName = vpnStats[i].networkName;
						}

						if ('networkId' in vpnStats[i].merakiVpnPeers[u]) {
							x.peerNetworkId = vpnStats[i].merakiVpnPeers[u].networkId;
						}
						if ('networkName' in vpnStats[i].merakiVpnPeers[u]) {
							x.peerNetworkName = vpnStats[i].merakiVpnPeers[u].networkName;
						}

						return x;
					});
					result = result.concat(vpn_stats);
				}
			}
		}
	}

	vpnStatuses = getHttpData(params.url + 'organizations/' + encodeURIComponent(params.organizationId) + '/appliance/vpn/statuses');

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

return JSON.stringify({
	'vpnStats': result,
	'vpnStatuses': vpnStatuses,
	'error': error_msg.toString()
});