var Util = require('libresignage/util/Util');
var Assert = require('assert');

/**
* Settings object for the Shortcut constructor.
*
* @typedef ShortcutSettings
*
* @property {string[]} keys  The names of the keys required for the shortcut.
* @property {function} hook  A hook function to execute when the shortcut is
*                            triggered.
* @property {function} defer A function that returns true if the shortcut hook
*                            should be executed. This function is called every
*                            time the shortcut is triggered.
*
* @memberof module:libresignage/misc
* @alias    ShortcutSettings
*/

/**
* A class representing a shortcut key combination.
*
* @memberof module:libresignage/misc
*/
class Shortcut {
	/**
	* Constrcut a new Shortcut object.
	*
	* @param {ShortcutSettings} settings
	*
	* @throws {AssertionError} If the settings object is missing keys.
	*/
	constructor(settings) {
		Assert.ok(
			Util.sets_eq(
				Object.keys(settings),
				['keys', 'hook', 'defer']
			),
			'Missing keys in Shortcut settings object.',
		);
		this.keys  = settings.keys;
		this.hook  = settings.hook;
		this.defer = settings.defer;
	}

	matches(keys) { return Util.sets_eq(keys, this.keys); }

	exec() {
		if (!this.defer || !this.defer()) {
			this.hook();
		} else {
			console.log(`Shortcut: '${this.keys.join(' + ')}' deferred.`);
		}
	}
}
module.exports = Shortcut;
