SubConfiguration.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using InABox.Core;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Text;
  7. namespace InABox.Configuration
  8. {
  9. public class SubConfiguration<T, TParent> : IConfiguration<T>
  10. where TParent : new()
  11. {
  12. public IConfiguration<TParent> Configuration { get; set; }
  13. private Func<TParent, T> Getter { get; set; }
  14. private Action<TParent, T> Setter { get; set; }
  15. public SubConfiguration(IConfiguration<TParent> configuration, Expression<Func<TParent, T>> expression)
  16. {
  17. Configuration = configuration;
  18. var property = CoreUtils.GetFullPropertyName(expression, ".");
  19. Getter = Expressions.Getter(expression);
  20. var setter = Expressions.Setter<TParent>(property);
  21. Setter = (parent, value) => setter(parent, value);
  22. }
  23. public string[] Sections() => Configuration.Sections();
  24. public T Load(bool useCache = true)
  25. {
  26. var parent = Configuration.Load(useCache);
  27. return Getter(parent);
  28. }
  29. public Dictionary<string, T> LoadAll(IEnumerable<string>? keys = null)
  30. {
  31. var parent = Configuration.LoadAll(keys);
  32. return parent.ToDictionary(x => x.Key, x => Getter(x.Value));
  33. }
  34. public void Save(T obj)
  35. {
  36. var parent = Configuration.Load(true);
  37. Setter(parent, obj);
  38. Configuration.Save(parent);
  39. }
  40. public void SaveAll(Dictionary<string, T> objs, bool reset = false)
  41. {
  42. var parents = Configuration.LoadAll(objs.Keys);
  43. foreach(var (key, obj) in objs)
  44. {
  45. var parent = parents.GetValueOrAdd(key);
  46. Setter(parent, obj);
  47. }
  48. Configuration.SaveAll(parents);
  49. }
  50. public void Delete(Action<Exception?>? callback = null)
  51. {
  52. var parent = Configuration.Load(true);
  53. Setter(parent, default);
  54. Configuration.Save(parent);
  55. }
  56. }
  57. }