using System; using System.Collections.Concurrent; using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace BITKit { public static class Data { [ExcuteOnStop] public static void Reload() { dictionary.Clear(); events.Clear(); } public static readonly Dictionary Objects = new(); public static readonly ConcurrentDictionary> rawEvents = new(); static readonly ConcurrentDictionary dictionary = new(); static readonly ConcurrentDictionary> events = new(); public static void AddListener(Action action, bool autoInvoke = false) => AddListener(Constant.System.Internal, action, autoInvoke); public static void RemoveListender(Action action) => RemoveListender(Constant.System.Internal, action); public static void Set(T value) => Set(Constant.System.Internal, value); public static void AddListener(string key, Action action, bool autoInvoke = false) { rawEvents.AddOrUpdate(key, x => new List() { action }, (x, y) => { y.Add(action); return y; }); key = Generic.GetVariable(key); events.Get(key).Add(action); if (autoInvoke) { if (dictionary.TryGetValue(key, out var value)) { if (value is T t) { action.Invoke(t); } } } } public static void RemoveListender(string key, Action action) { var list = rawEvents.GetOrAdd(key, x => new()); list.TryRemove(action); key = Generic.GetVariable(key); events.Get(key).Remove(action); } public static void Set(string key, Func factory) { key = Generic.GetVariable(key); dictionary.AddOrUpdate(key,factory, AddOrUpdate); return; Func AddOrUpdate(string _key,object current) { return factory; } } public static void Set(string key, T value) { key = Generic.GetVariable(key); if (dictionary.ContainsKey(key)) { dictionary.AddOrUpdate(key, (x) => value, (x, y) => value); } else { dictionary.GetOrAdd(key, value); } var list = events.Get(key); list.ToArray().ForEach(x => { var action = x as Action; action.Invoke(value); }); if (value is not JToken) Objects.TryInsert(key, value); } public static bool TryGetValue(string key, out T value) { key = Generic.GetVariable(key); if (dictionary.TryGetValue(key, out var _value)) { if (_value is T t) { value = t; return true; } } value = default; return false; } public static T Get(string key = Constant.System.Internal) { key = Generic.GetVariable(key); if (dictionary.TryGetValue(key, out var value)) { switch (value) { case T t: return t; case Func func: return func.Invoke(); } } return default; } public static void Clear() { dictionary.Clear(); } public static void Clear() { ConcurrentDictionary copy = new(dictionary); object output; foreach (var item in copy) { if (item.Value is T) { dictionary.Remove(item.Key, out output); } } } } }