'use strict';

var EventEmitter = require('events').EventEmitter;

// Available updaters
var updatersNames = ['dummy', /*'rate',*/ 'rate-simple', 'stabilize-simple', 'physics'];

// require() updaters
var updaters = {};
updatersNames.forEach(function (name) {
	updaters[name] = require('./'+name);
});

var currentUpdater = Symbol();

class Controller extends EventEmitter {
	constructor(quad) {
		super();

		this.quad = quad;

		// Instanciate updaters
		this.updaters = {};
		for (var updaterName in updaters) {
			var updater = new updaters[updaterName](quad);

			// Ensure each updater has a valid target
			updater.setTarget({ x: 0, y: 0, z: 0 });

			this.updaters[updaterName] = updater;
		}
	}

	[currentUpdater]() {
		var updaterName = this.quad.config.controller.updater;
		return this.updaters[updaterName];
	}

	/**
	 * Update the controller target.
	 */
	setTarget(target) {
		this[currentUpdater]().setTarget(target);
	}

	/**
	 * Reset the controller.
	 */
	reset() {
		this[currentUpdater]().reset();
	}

	/**
	 * Feed the controller with new data from sensors,
	 * and get the new correction for motors.
	 * Returns an object containg x, y, z keys with forces delta.
	 */
	update(data) {
		var updaterName = this.quad.config.controller.updater;

		// IMU not available OR quadcopter on ground:
		// Do not use PIDs
		if (!data/* || this.quad.power <= 0.2*/) {
			updaterName = 'dummy';
		}

		// Get the result from the currently enabled updater
		// If the updater returns a string, use this string as updater
		// TODO: deprecate this feature?
		var result;
		while (true) {
			var updater = this.updaters[updaterName];
			if (!updater) {
				throw new Error('Updater '+updaterName+' not available');
			}

			result = updater.update(data);
			if (typeof result == 'string') {
				updaterName = result;
			} else {
				break;
			}
		}

		return result;
	}

	static get available() {
		return updatersNames;
	}
}

module.exports = Controller;

@@ -401,16 +401,35 @@
 per();%0A%0A
+%09%09var that = this;%0A
 %09%09this.q
@@ -713,19 +713,229 @@
 er;%0A%09%09%7D%0A
-%09%7D%0A
+%0A%09%09// Reset controllers when the quad is turned off%0A%09%09quad.on('enabled', function (val) %7B%0A%09%09%09if (!val) %7B%0A%09%09%09%09that.reset();%0A%09%09%09%7D%0A%09%09%7D);%0A%09%7D%0A%0A%09/**%0A%09 * Get the current updater.%0A%09 * @return BaseUpdater%0A%09 * @private%0A%09 */
 %0A%09%5Bcurre
@@ -1209,38 +1209,72 @@
 t() %7B%0A%09%09
-this%5BcurrentUpdater%5D()
+for (var name in this.updaters) %7B%0A%09%09%09this.updaters%5Bname%5D
 .reset()
@@ -1275,16 +1275,20 @@
 eset();%0A
+%09%09%7D%0A
 %09%7D%0A%0A%09/**
@@ -2138,16 +2138,75 @@
 lt;%0A%09%7D%0A%0A
+%09/**%0A%09 * Get available updaters.%0A%09 * @return String%5B%5D%0A%09 */%0A
 %09static 

Reset updater when powering off the quad