/**
* A hook function for running code when a validation state changes.
*
* @callback ValidatorTrigger_trigger_hook
*
* @param {boolean} state The validation state of the attached Validators.
*/

/**
* An object that calls a hook function when the validation state
* of a set of ValidatorSelector objects changes.
*
* @memberof module:libresignage/ui/validator
*/
class ValidatorTrigger {
	/**
	* Construct a new ValidatorTrigger object.
	*
	* @param {ValidatorSelector[]}           selectors ValidatorSelector array.
	* @param {ValidatorTrigger_trigger_hook} hook      The hook function to use.
	*/
	constructor(selectors, hook) {
		this.valid = null;
		this.hook = hook;
		this.selectors = selectors;

		for (let s of this.selectors) {
			s.add_hook(sel => this.trigger());
		}

		// Take initial validation state into account.
		this.trigger();
	}

	/**
	* Check the validation state of the registered ValidatorSelectors
	* and call the hook function if needed.
	*/
	trigger() {
		let tmp = true;
		for (let s of this.selectors) {
			tmp = tmp && s.get_state();
			if (!tmp) { break; }
		}
		this.valid = tmp;
		if (this.hook) { this.hook(this.valid); }
	}

	/**
	* Check whether a ValidatorTrigger is valid.
	*
	* @return {boolean} True = valid, false = invalid.
	*/
	is_valid() { return this.valid; }

	/**
	* Validate all ValidatorSelectors attached to a trigger.
	*/
	validate_all() {
		for (let s of this.selectors) {
			s.validate();
		}
	}
}
module.exports = ValidatorTrigger;
