const utils = require('.');
let actions = {
generic: []
};
module.exports = {
/*
trigger: function(invoke) {
Invoke callback to trigger action
}
action: function () {
Invoked when trigger invokes callback.
Return true for single time action, or false for permanent action
}
options: {
type: set type of action. Used to group multiple action checks
id: override action id to reference explicitly throughout codebase
delete: bool to delete an action. type and id cannot be undefined
}
*/
register: function(trigger, action, options) {
options = options || {};
let type = options.type || "generic";
if (!actions[type]) {
actions[type] = {};
}
let id = options.id || utils.uuid();
if (actions[type][id]) {
if (options.delete) {
delete actions[type][id];
console.log(`Action "${id}" for ${type} deleted`);
return;
} else {
console.log(`Action "${id}" for ${type} overriden`);
}
} else {
console.log(`New action "${id}" registered for ${type}`);
}
actions[type][id] = function() {
trigger(function() {
console.log(`Action "${id}" invoked`);
if (action()) {
console.log(`Delete single time action "${id}"`);
delete actions[type][id];
}
});
};
return {
type: type,
id: id
};
},
check: function(type, id) {
if (!actions[type]) {
console.log(`No actions registered for ${type}`);
return;
}
if (id) {
console.log(`Check command "${id}" for ${type}`);
actions[type][id]();
} else {
console.log(`Check commands for ${type}`);
Object.entries(actions[type]).forEach(function([id, command]) {
console.log(`Check command "${id}"`);
command();
});
}
}
};