Files
elwig/Elwig/Helpers/Config.cs
2023-08-11 22:18:28 +02:00

88 lines
3.3 KiB
C#

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using IniParser;
using IniParser.Model;
namespace Elwig.Helpers {
public class Config {
private readonly string FileName;
public string DatabaseFile = App.DataPath + "database.sqlite3";
public string? DatabaseLog = null;
public string? Branch = null;
public IList<string?[]> Scales;
private readonly List<string?[]> ScaleList = new();
public Config(string filename) {
FileName = filename;
Scales = ScaleList;
Read();
}
public void Read() {
var parser = new FileIniDataParser();
IniData? ini = null;
try {
ini = parser.ReadFile(FileName, Encoding.UTF8);
} catch {}
if (ini == null || !ini.TryGetKey("database.file", out string db)) {
DatabaseFile = App.DataPath + "database.sqlite3";
} else if (db.Length > 1 && (db[1] == ':' || db[0] == '/' || db[0] == '\\')) {
DatabaseFile = db;
} else {
DatabaseFile = App.DataPath + db;
}
if (ini == null || !ini.TryGetKey("database.log", out string log)) {
DatabaseLog = null;
} else if (log.Length > 1 && (log[1] == ':' || log[0] == '/' || log[0] == '\\')) {
DatabaseLog = log;
} else {
DatabaseLog = App.DataPath + log;
}
if (ini == null || !ini.TryGetKey("general.branch", out string branch)) {
Branch = null;
} else {
Branch = branch;
}
ScaleList.Clear();
Scales = ScaleList;
if (ini != null) {
foreach (var s in ini.Sections.Where(s => s.SectionName.StartsWith("scale."))) {
string? scaleLog = null;
if (s.Keys["log"] != null) {
scaleLog = s.Keys["log"];
if (scaleLog.Length <= 1 || (scaleLog[1] != ':' && scaleLog[0] != '/' && scaleLog[0] != '\\')) {
scaleLog = App.DataPath + scaleLog;
}
}
ScaleList.Add(new string?[] {
s.SectionName[6..], s.Keys["type"], s.Keys["model"], s.Keys["connection"],
s.Keys["empty"], s.Keys["filling"], s.Keys["limit"], scaleLog
});
}
}
}
public void Write() {
using var file = new StreamWriter(FileName, false, Encoding.UTF8);
file.Write($"\r\n[general]\r\n");
if (Branch != null) file.Write($"branch = {Branch}\r\n");
file.Write($"\r\n[database]\r\nfile = {DatabaseFile}\r\n");
if (DatabaseLog != null) file.Write($"log = {DatabaseLog}\r\n");
foreach (var s in ScaleList) {
file.Write($"\r\n[scale.{s[0]}]\r\ntype = {s[1]}\r\nmodel = {s[2]}\r\nconnection = {s[3]}\r\n");
if (s[4] != null) file.Write($"empty = {s[4]}\r\n");
if (s[5] != null) file.Write($"filling = {s[5]}\r\n");
if (s[6] != null) file.Write($"limit = {s[6]}\r\n");
if (s[7] != null) file.Write($"log = {s[7]}\r\n");
}
}
}
}