Files
SethDiscordBot/DiscordBotCore/Others/SettingsDictionary.cs
2024-06-08 20:47:15 +03:00

116 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace DiscordBotCore.Others;
public class SettingsDictionary<TKey, TValue>
{
private string _File { get; }
protected IDictionary<TKey, TValue> _Dictionary;
public SettingsDictionary(string file)
{
this._File = file;
_Dictionary = null!;
}
public async Task SaveToFile()
{
if (!string.IsNullOrEmpty(_File))
await JsonManager.SaveToJsonFile(_File, _Dictionary);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _Dictionary.GetEnumerator();
}
public async Task<bool> LoadFromFile()
{
if (string.IsNullOrEmpty(_File))
return false;
if(!File.Exists(_File))
{
_Dictionary = new Dictionary<TKey, TValue>();
await SaveToFile();
return false;
}
string fileAsText = await File.ReadAllTextAsync(_File);
if(string.IsNullOrEmpty(fileAsText) || string.IsNullOrWhiteSpace(fileAsText))
{
_Dictionary = new Dictionary<TKey, TValue>();
await SaveToFile();
return false;
}
_Dictionary = await JsonManager.ConvertFromJson<IDictionary<TKey,TValue>>(fileAsText);
if (_Dictionary.Keys.Count == 0)
return false;
return true;
}
public void Add(TKey key, TValue value)
{
_Dictionary.Add(key, value);
}
public bool ContainsAllKeys(params TKey[] keys)
{
return keys.All(key => _Dictionary.ContainsKey(key));
}
public bool ContainsKey(TKey key)
{
return _Dictionary.ContainsKey(key);
}
public bool Remove(TKey key)
{
return _Dictionary.Remove(key);
}
public TValue this[TKey key]
{
get
{
if(!_Dictionary.ContainsKey(key))
throw new System.Exception($"The key {key} ({typeof(TKey)}) (file: {this._File}) was not present in the dictionary");
if(_Dictionary[key] is not TValue)
throw new System.Exception("The dictionary is corrupted. This error is critical !");
return _Dictionary[key];
}
set => _Dictionary[key] = value;
}
// First
public KeyValuePair<TKey, TValue> FirstOrDefault(Func<KeyValuePair<TKey, TValue>, bool> predicate)
{
return _Dictionary.FirstOrDefault(predicate);
}
// Where
public IEnumerable<KeyValuePair<TKey, TValue>> Where(Func<KeyValuePair<TKey, TValue>, bool> predicate)
{
return _Dictionary.Where(predicate);
}
public void Clear()
{
_Dictionary.Clear();
}
public IEnumerable<TKey> Keys => _Dictionary.Keys;
public IEnumerable<TValue> Values => _Dictionary.Values;
}