var UIElem = require('libresignage/ui/controller/UIElem');
var Assert = require('assert');

/**
* UIInput settings object.
*
* More settings documented at {@link module:libresignage/ui/controller.UIElem#UIElemSettings}
*
* @property {function} mod     A callback that returns true if the input has
*                              been modified. The current value of the input is
*                              passed as the first argument.
* @property {function} getter  A getter function that returns the value of
*                              the input. The HTMLElement object is passed
*                              as the first argument.
* @property {function} setter  A setter function that sets the value of
*                              the input. The HTMLElement is passed as the
*                              first argument and the new value as the second
*                              one.
* @property {function} clearer A function that clears the input.
*
* @typedef {object} module:libresignage/ui/controller.UIInput#UIInputSettings
*
* @memberof module:libresignage/ui/controller
*/

/**
* UI class for DOM input elements.
*
* @memberof module:libresignage/ui/controller
*/
class UIInput extends UIElem {
	/**
	* Construct a new UIInput object.
	*
	* @param {module:libresignage/ui/controller.UIInput#UIInputSettings}
	*	settings
	*	Settings object.
	*
	* @throws {AssertionError} If mod, getter, setter and clearer are not defined
	*                       in the settings object.	
	*/
	constructor(settings) {
		super(settings);
		Assert.ok('mod' in settings);
		Assert.ok('getter' in settings);
		Assert.ok('setter' in settings);
		Assert.ok('clearer' in settings);

		this.type = "input";

		this.mod = settings.mod;
		this.getter = settings.getter;
		this.setter = settings.setter;
		this.clearer = settings.clearer;
	}

	/**
	* Return the value of an input.
	*
	* @return {mixed|null} The value of the input or null if a getter
	*                      is not defined.
	*/
	get() {
		if (this.getter) {
			return this.getter(this.get_elem());
		} else {
			return null;
		}
	}

	/**
	* Set the value of an input.
	*/
	set(data) {
		if (this.setter) {
			this.setter(this.get_elem(), data);
		}
	}

	/**
	* Check whether an input is modified.
	*
	* @return {boolean} True if input is modified, false otherwise.
	*/
	is_mod(data) {
		if (this.mod) {
			return this.mod(this.get_elem(), data);
		} else {
			return false;
		}
	}

	/**
	* Clear an input.
	*/
	clear() {
		if (this.clearer) {
			this.clearer(this.get_elem());
		}
	}
}
module.exports = UIInput;
