RCM/RCM/Config.cs

85 lines
3.5 KiB
C#

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
namespace RCM {
public static class Config {
private static readonly string _dirName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RCM");
private static readonly string _fileName = Path.Combine(_dirName, "RCM.conf");
private static Icon _emptyIcon;
public static ImageList IconList { get; } = new ImageList() { ColorDepth = ColorDepth.Depth32Bit, ImageSize = new Size(20, 20) };
public static List<Type> DataSourceTypes { get; } = new List<Type>();
public static List<Type> RecordTypes { get; } = new List<Type>();
public static List<IDataSource> DataSources { get; } = new List<IDataSource>();
public static Dictionary<Type, IConfigSection> ConfigSections { get; } = new Dictionary<Type, IConfigSection>();
private static List<JObject> _uknownSections = new List<JObject>();
public static void LoadModules() {
_emptyIcon = (Icon)new ComponentResourceManager(typeof(Config)).GetObject("EmptyIcon");
IEnumerable<Type> types = Assembly.GetExecutingAssembly().GetTypes().Where(type => !type.IsInterface);
foreach (Type type in types) {
if (typeof(IDataSource).IsAssignableFrom(type)) {
DataSourceTypes.Add(type);
AddIconForType(type);
} else if (typeof(IRecord).IsAssignableFrom(type)) {
RecordTypes.Add(type);
AddIconForType(type);
} else if (typeof(IConfigSection).IsAssignableFrom(type)) {
ConfigSections[type] = (IConfigSection)Activator.CreateInstance(type);
}
}
}
public static void AddIconForType(Type type) {
try {
IconList.Images.Add(type.FullName, (Icon)new ComponentResourceManager(type).GetObject("Icon"));
} catch {
IconList.Images.Add(type.FullName, _emptyIcon);
}
}
public static void LoadConfiguration() {
if (File.Exists(_fileName)) {
JArray json = JArray.Parse(File.ReadAllText(_fileName));
foreach (JObject section in json) {
try {
LoadSection(section);
} catch {
_uknownSections.Add(section);
}
}
}
}
private static void LoadSection(JObject section) {
object obj = ConfigSerializer.JsonToObj(section);
if (obj is IDataSource dataSource) {
DataSources.Add(dataSource);
} else if (obj is IConfigSection configSection) {
ConfigSections[configSection.GetType()] = configSection;
}
}
public static void Save() {
JArray json = new JArray(DataSources.Select(dataSource => ConfigSerializer.ObjToJson(dataSource))
.Union(ConfigSections.Values.Select(configSection => ConfigSerializer.ObjToJson(configSection)))
.Union(_uknownSections));
if (!Directory.Exists(_dirName)) {
Directory.CreateDirectory(_dirName);
}
File.WriteAllText(_fileName, ConfigSerializer.JsonToString(json));
}
}
}