12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- using InABox.Core;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Text;
- namespace InABox.Configuration
- {
- public class SubConfiguration<T, TParent> : IConfiguration<T>
- where TParent : new()
- {
- public IConfiguration<TParent> Configuration { get; set; }
- private Func<TParent, T> Getter { get; set; }
- private Action<TParent, T> Setter { get; set; }
- public SubConfiguration(IConfiguration<TParent> configuration, Expression<Func<TParent, T>> expression)
- {
- Configuration = configuration;
- var property = CoreUtils.GetFullPropertyName(expression, ".");
- Getter = Expressions.Getter(expression);
- var setter = Expressions.Setter<TParent>(property);
- Setter = (parent, value) => setter(parent, value);
- }
- public string[] Sections() => Configuration.Sections();
- public T Load(bool useCache = true)
- {
- var parent = Configuration.Load(useCache);
- return Getter(parent);
- }
- public Dictionary<string, T> LoadAll(IEnumerable<string>? keys = null)
- {
- var parent = Configuration.LoadAll(keys);
- return parent.ToDictionary(x => x.Key, x => Getter(x.Value));
- }
- public void Save(T obj)
- {
- var parent = Configuration.Load(true);
- Setter(parent, obj);
- Configuration.Save(parent);
- }
- public void SaveAll(Dictionary<string, T> objs, bool reset = false)
- {
- var parents = Configuration.LoadAll(objs.Keys);
- foreach(var (key, obj) in objs)
- {
- var parent = parents.GetValueOrAdd(key);
- Setter(parent, obj);
- }
- Configuration.SaveAll(parents);
- }
- public void Delete(Action<Exception?>? callback = null)
- {
- var parent = Configuration.Load(true);
- Setter(parent, default);
- Configuration.Save(parent);
- }
- }
- }
|