diff --git a/Mage/Module.cs b/Mage/Module.cs index 460aeff..272e651 100644 --- a/Mage/Module.cs +++ b/Mage/Module.cs @@ -8,29 +8,39 @@ namespace Wizcorp.MageSDK.MageClient { - - public class Module : Singleton where T : class, new() + using MageCommandAction = Action>; + using MageCommandFunction = Func; + + public abstract class Module : Singleton where T : class, new() { - // + // Tells us if the module was set up + protected bool SetupCompleted = false; + + // Mage singleton accessor protected Mage Mage { get { return Mage.Instance; } } + // Contextualized logger protected Logger Logger { get { return Mage.Logger(GetType().Name); } } - - // + // Static protected virtual List StaticTopics { - get { return null; } + get { return new List {}; } } + // Static data container public JToken StaticData; + // Static data setup + // Note that topics are not tied to MAGE modules; they are + // essentially global to the MAGE server instance. This is + // simply a convenience function for public void SetupStaticData(Action cb) { Logger.Info("Setting up static data"); @@ -67,28 +77,46 @@ public void SetupStaticData(Action cb) } - // - protected virtual string CommandPrefix - { - get { return null; } - } + // The module name as defined on the remote MAGE server + protected abstract string CommandPrefix { get; } - protected virtual List Commands + // The list of available user commands on the remote MAGE server + protected abstract List Commands { get; } + + private Dictionary commandHandlerActions; + private Dictionary commandHandlerFuncs; + + private void AssertSetupCompleted() { - get { return null; } + if (SetupCompleted == false) + { + throw new Exception("This module was not setup: " + CommandPrefix); + } } - private Dictionary>> commandHandlerActions; - private Dictionary> commandHandlerFuncs; + private M GetCommand(Dictionary list, string commandName) { + AssertSetupCompleted(); + + var command = list[commandName]; + + if (command == null) + { + throw new Exception("User command not found: " + CommandPrefix + "." + commandName); + } + + return command; + } public void Command(string commandName, JObject arguments, Action cb) { - commandHandlerActions[commandName](arguments, cb); + var action = GetCommand(commandHandlerActions, commandName); + action(arguments, cb); } public UserCommandStatus Command(string commandName, JObject arguments) { - return commandHandlerFuncs[commandName](arguments); + var action = GetCommand(commandHandlerFuncs, commandName); + return action(arguments); } private void RegisterCommand(string command) @@ -126,17 +154,12 @@ public void SetupUsercommands(Action cb) commandHandlerActions = new Dictionary>>(); commandHandlerFuncs = new Dictionary>(); - if (Commands == null) - { - cb(null); - return; - } - foreach (string command in Commands) { RegisterCommand(command); } + SetupCompleted = true; cb(null); } }