using System; using System.Collections.Generic; using System.Linq; using NBC; namespace NBF { public class Command { public enum LogType { Info, Warn, Error } public struct LogData { public string Log; public LogType Type; public LogData(string log, LogType type) { Log = log; Type = type; } } private static readonly Dictionary _commands = new Dictionary(); #region Log public static readonly List Logs = new List(); private const int MaxLog = 1000; public static Action OnLogChange; public static void LogInfo(string log) { AddLog(log, LogType.Info); } public static void LogWarn(string log) { AddLog(log, LogType.Warn); } public static void LogError(string log) { AddLog(log, LogType.Error); } private static void AddLog(string log, LogType type) { if (Logs.Count > MaxLog) { var sub = Logs.Count - MaxLog; for (int i = 0; i < sub; i++) { Logs.RemoveAt(0); } } Logs.Add(new LogData(log, type)); OnLogChange?.Invoke(); } #endregion /// /// 反射所有GM命令 /// public static void Init() { try { var assembly = AppDomain.CurrentDomain.GetAssemblies() .First(a => a.GetName().Name == "Assembly-CSharp"); var type = typeof(ICommand); var types = assembly.GetTypes(); Log.Info("command 6"); var commandTypes = types.Where(u => type.IsAssignableFrom(u) && u.IsClass && !u.IsAbstract && !u.IsGenericType); foreach (var c in commandTypes) { if (Activator.CreateInstance(c) is ICommand command) { _commands[command.Command] = command; } } } catch (Exception e) { Log.Error(e); } } public static void Open() { // UI.Inst.OpenUI(); } public static void Close() { // UI.Inst.DestroyUI(); } public static bool Has(string command) { return _commands.ContainsKey(command); } /// /// 获取所有指令实例 /// /// public static List GetAll() { return _commands.Values.ToList(); } public static ICommand Get(string command) { return _commands.GetValueOrDefault(command); } /// /// 执行命令 /// /// /// public static bool Run(string command) { var args = new CommandArgs(command); var inst = Get(args.Command); return inst?.Execute(args) ?? false; } /// /// 匹配相识的命令 /// /// /// public static List Match(string command) { var list = new List(); foreach (var key in _commands.Keys) { if (key.Contains(command)) { list.Add(_commands[key]); } } return list; } } }