/**
* A class for creating and managing timeouts.
*
* @memberof module:libresignage/misc
*/
class Timeout {
	/**
	* Construct a new Timeout object.
	*
	* @param {function} hook A hook that's called once the set time has passed.
	* @param {number}   t    The length of the timeout in milliseconds.
	*/
	constructor(hook, t) {
		this.id = setTimeout(() => {
			this.hook();
			this.id = null;
		}, t);

		this.hook = hook;
		this.t = t;
		this.canceled = false;
	}

	/**
	* Manually execute a timeout.
	*/
	exec() {
		if (this.id != null) {
			this.cancel();
			this.hook();
		}
	}

	/**
	* Cancel a timeout.
	*/
	cancel() {
		if (this.id != null) {
			clearTimeout(this.id);
			this.id = null;
			this.canceled = true;
		}
	}

	/**
	* Check whether a Timeout is active.
	*
	* @returns {boolean} True if the Timeout is active, False otherwise.
	*/
	is_active()   { return this.id != null && !this.canceled}

	/**
	* Check whether a Timeout has been executed.
	*
	* @returns {boolean} True if the Timeout has been executed, False otherwise.
	*/
	is_execd()    { return this.id == null && !this.canceled }

	/**
	* Check whether a timeout has been cancelled.
	*
	* @returns {boolean} True if the Timeout has been cancelled,
	*                    False otherwise.
	*/
	is_canceled() { return this.canceled; }
}
module.exports = Timeout;
