var data = JSON.parse(value),
	metrics = [],
	alarms = [],
	error;

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;
};

var result = data.results[1];

if (typeof result[error] === undefined || result['rpc-reply'] !== undefined) {

	var dom = getField(result, 'rpc-reply.interface-information.physical-interface');

	dom.forEach(function (item) {
		var name = getField(item, 'name'),
			diagnostics = getField(item, 'optics-diagnostics'),
			lane_values = getField(diagnostics, 'optics-diagnostics-lane-values');

		if (lane_values) {
			lane_values.forEach(function (lane) {
				metrics.push({
					name: name,
					lane_index: getField(lane, 'lane-index'),
					multi: 1,
					tx_power: getField(lane, 'laser-output-power-dbm'),
					rx_power: getField(lane, 'laser-rx-optical-power')
				});

				alarms.push({
					name: name,
					lane_index: getField(lane, 'lane-index'),
					tx_loss_signal: getField(lane, 'tx-loss-of-signal-functionality-alarm'),
					tx_laser_disabled: getField(lane, 'tx-laser-disabled-alarm'),
					bias_high: getField(lane, 'laser-bias-current-high-alarm'),
					bias_low: getField(lane, 'laser-bias-current-low-alarm'),
					rx_loss_signal: getField(lane, 'rx-loss-of-signal-alarm'),
					rx_high: getField(lane, 'laser-rx-power-high-alarm'),
					rx_low: getField(lane, 'laser-rx-power-low-alarm'),
					voltage_high: getField(diagnostics, 'module-voltage-high-alarm'),
					voltage_low: getField(diagnostics, 'module-voltage-low-alarm'),
					temperature_high: getField(diagnostics, 'module-temperature-high-alarm'),
					temperature_low: getField(diagnostics, 'module-temperature-low-alarm')
				});
			});
		} else {
			metrics.push({
				name: name,
				lane_index: 0,
				multi: 0,
				tx_power: getField(diagnostics, 'laser-output-power-dbm'),
				rx_power: getField(diagnostics, 'rx-signal-avg-optical-power-dbm')
			});
			alarms.push({
				name: name,
				lane_index: 0,
				bias_high: getField(diagnostics, 'laser-bias-current-high-alarm'),
				bias_low: getField(diagnostics, 'laser-bias-current-low-alarm'),
				rx_high: getField(diagnostics, 'laser-rx-power-high-alarm'),
				rx_low: getField(diagnostics, 'laser-rx-power-low-alarm'),
				tx_high: getField(diagnostics, 'laser-tx-power-high-alarm'),
				tx_low: getField(diagnostics, 'laser-tx-power-low-alarm'),
				voltage_high: getField(diagnostics, 'module-voltage-high-alarm'),
				voltage_low: getField(diagnostics, 'module-voltage-low-alarm'),
				temperature_high: getField(diagnostics, 'module-temperature-high-alarm'),
				temperature_low: getField(diagnostics, 'module-temperature-low-alarm')
			});
		}
	});
}
else {
	error = result.content;
};

return JSON.stringify({ metrics, alarms, error });