var data = JSON.parse(value),
	bgp = [],
	bgp_peers = [],
	bgp_rib = [];

function getField(data, path, default_value) {
	var steps = path.split('.');
	var step = steps.shift();

	while (typeof step !== 'undefined') {
		if (typeof data === undefined || typeof data[step] === 'undefined') {
			return default_value;
		}

		data = data[step];
		step = steps.shift();
	}
	return data;
};

data.forEach(function (item) {
	var name = getField(item, 'name'),
		bgp_information = getField(item, 'bgp-information', {}),
		bgp_peer = getField(bgp_information, 'bgp-peer', {}),
		bgp_peer = Array.isArray(bgp_peer) ? bgp_peer : [bgp_peer],
		output = getField(item, 'output');

	if (bgp_peer && output !== "BGP is not running") {
		bgp_peer.forEach(function (peer) {
			var peer_rib = getField(peer, 'bgp-rib', {});
			var peer_rib = Array.isArray(peer_rib) ? peer_rib : [peer_rib];
			bgp_peers.push({
				router_name: name,
				peer_address: getField(peer, 'peer-address'),
				peer_as: getField(peer, 'peer-as'),
				elapsed_time: getField(peer, 'elapsed-time.@seconds'),
				flap_count: getField(peer, 'flap-count'),
				bgp_thread_mode: getField(bgp_information, 'bgp-thread-mode'),
				peer_state: getField(peer, 'peer-state.#text')
			});
			peer_rib.forEach(function (rib) {
				bgp_rib.push({
					router_name: name,
					name: getField(rib, 'name'),
					peer_address: getField(peer, 'peer-address'),
					peer_as: getField(peer, 'peer-as'),
					suppressed: getField(rib, 'suppressed-prefix-count'),
					received: getField(rib, 'received-prefix-count'),
					active: getField(rib, 'active-prefix-count'),
					accepted: getField(rib, 'accepted-prefix-count')
				});
			});

		});
		bgp.push({
			router_name: name,
			down_peer_count: getField(bgp_information, 'down-peer-count'),
			peer_count: getField(bgp_information, 'peer-count'),
			bgp_thread_mode: getField(bgp_information, 'bgp-thread-mode')
		});
	}
});

return JSON.stringify({ bgp, bgp_peers, bgp_rib });