using Newtonsoft.Json;
using System;
using System.IO;
namespace TShockAPI.Configuration
{
///
/// Implements to provide a generic config file containing some settings
///
///
public class ConfigFile : IConfigFile
{
///
/// Settings managed by this config file
///
public virtual TSettings Settings { get; set; }
///
/// Action invoked when the config file is read
///
public static Action> OnConfigRead;
///
/// Reads json-formatted settings from a given path
///
/// The path to the file containing the settings
///
/// Whether the config object has any new fields in it, meaning that the config file has to be
/// overwritten.
///
/// Settings object
public virtual TSettings Read(string path, out bool incompleteSettings)
{
if (!File.Exists(path))
{
incompleteSettings = true;
return default;
}
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return Read(fs, out incompleteSettings);
}
}
///
/// Reads json-formatted settings from a given stream
///
/// stream
///
/// Whether the config object has any new fields in it, meaning that the config file has to be
/// overwritten.
///
/// Settings object
public virtual TSettings Read(Stream stream, out bool incompleteSettings)
{
using (var sr = new StreamReader(stream))
{
return ConvertJson(sr.ReadToEnd(), out incompleteSettings);
}
}
///
/// Converts a json-formatted string into the settings object used by this configuration
///
/// Json string to parse
/// Whether or not the json string contained an incomplete set of settings
/// Settings object
public virtual TSettings ConvertJson(string json, out bool incompleteSettings)
{
var settings = FileTools.LoadConfigAndCheckForMissingFields(json, out incompleteSettings);
Settings = settings;
OnConfigRead?.Invoke(this);
return settings;
}
///
/// Writes the configuration to a given path
///
/// string path - Location to put the config file
public virtual void Write(string path)
{
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write))
{
Write(fs);
}
}
///
/// Writes the configuration to a stream
///
/// stream
public virtual void Write(Stream stream)
{
var str = JsonConvert.SerializeObject(this, Formatting.Indented);
using (var sw = new StreamWriter(stream))
{
sw.Write(str);
}
}
}
}