EliteBGS/Util/Config.cs

90 lines
3.1 KiB
C#
Raw Normal View History

2021-07-09 11:03:30 +02:00
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Newtonsoft.Json;
2021-11-10 21:24:39 +01:00
using EliteBGS.BGS;
2021-07-09 11:03:30 +02:00
2021-11-10 21:24:39 +01:00
namespace EliteBGS.Util {
2021-07-09 11:03:30 +02:00
public class Config {
private string config_folder = null;
private string objectives_file = null;
private string config_file = null;
private AppConfig global_config = new AppConfig();
public Config() {
DetermineConfigFolder();
global_config.PropertyChanged += Global_config_PropertyChanged;
}
private void Global_config_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) {
try {
SaveGlobal();
} catch (Exception) {
/* ignored */
}
}
public string ConfigPath => config_folder;
public AppConfig Global => global_config;
private void DetermineConfigFolder() {
2021-11-10 21:24:39 +01:00
string folder = Environment.ExpandEnvironmentVariables("%appdata%\\EliteBGS");
2021-07-09 11:03:30 +02:00
if (!Directory.Exists(folder)) {
Directory.CreateDirectory(folder);
}
config_folder = folder;
objectives_file = Path.Combine(config_folder, "objectives.json");
config_file = Path.Combine(config_folder, "config.json");
}
public void SaveGlobal() {
var serializer = JsonSerializer.CreateDefault();
using (var file = new StreamWriter(File.OpenWrite(config_file), Encoding.UTF8)) {
var stream = new JsonTextWriter(file);
serializer.Serialize(stream, global_config);
}
}
public void LoadGlobal() {
var serializer = JsonSerializer.CreateDefault();
using (var file = new StreamReader(File.OpenRead(config_file), Encoding.UTF8)) {
var stream = new JsonTextReader(file);
var app = serializer.Deserialize<AppConfig>(stream);
if (app != null) {
this.global_config = app;
global_config.PropertyChanged += Global_config_PropertyChanged;
}
}
}
public void SaveObjectives(Report report) {
var serializer = JsonSerializer.CreateDefault();
2022-01-09 11:33:09 +01:00
using (FileStream filestream = File.OpenWrite(objectives_file)) {
filestream.SetLength(0);
filestream.Flush();
using (StreamWriter file = new StreamWriter(filestream, Encoding.UTF8)) {
JsonTextWriter stream = new JsonTextWriter(file);
serializer.Serialize(stream, report.Objectives);
}
2021-07-09 11:03:30 +02:00
}
}
public void LoadObjectives(Report report) {
var serializer = JsonSerializer.CreateDefault();
using (var file = new StreamReader(File.OpenRead(objectives_file), Encoding.UTF8)) {
var stream = new JsonTextReader(file);
var objectives = serializer.Deserialize<List<Objective>>(stream);
report.Objectives = objectives;
}
}
}
}