cs-codex-dist-tests/Tools/BiblioTech/Rewards/CustomReplacement.cs

79 lines
2.0 KiB
C#
Raw Normal View History

2024-07-02 08:37:32 +00:00
using Newtonsoft.Json;
namespace BiblioTech.Rewards
{
public class CustomReplacement
{
private readonly Dictionary<string, string> replacements = new Dictionary<string, string>();
2024-07-02 08:37:32 +00:00
private readonly string file;
public CustomReplacement(Configuration config)
{
file = Path.Combine(config.DataPath, "logreplacements.json");
}
public void Load()
{
replacements.Clear();
if (!File.Exists(file)) return;
var replaces = JsonConvert.DeserializeObject<ReplaceJson[]>(File.ReadAllText(file));
if (replaces == null) return;
foreach (var replace in replaces)
{
replacements.Add(replace.From, replace.To);
}
}
public void Add(string from, string to)
{
if (replacements.ContainsKey(from))
{
replacements[from] = to;
}
else
{
replacements.Add(from, to);
}
2024-07-02 08:37:32 +00:00
Save();
}
public void Remove(string from)
{
replacements.Remove(from);
2024-07-02 08:37:32 +00:00
Save();
}
public string Apply(string msg)
{
var result = msg;
foreach (var pair in replacements)
{
2024-07-03 17:11:21 +00:00
result = result.Replace(pair.Key, pair.Value);
}
return result;
}
2024-07-02 08:37:32 +00:00
private void Save()
{
ReplaceJson[] replaces = replacements.Select(pair =>
{
return new ReplaceJson
{
From = pair.Key,
To = pair.Value
};
}).ToArray();
File.WriteAllText(file, JsonConvert.SerializeObject(replaces));
}
private class ReplaceJson
{
public string From { get; set; } = string.Empty;
public string To { get; set; } = string.Empty;
}
}
}