chaosbot/ChaosBot/Configuration.cs

85 lines
3.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ChaosBot.Repositories;
using Microsoft.Extensions.Configuration;
namespace ChaosBot
{
public class Configuration
{
private readonly IConfiguration _appSettingsWrapper;
private static readonly Dictionary<string, Type> ConfigurationFlags = new Dictionary<string, Type>
{
{"Bot:Name", typeof(string)},
{"Bot:Version", typeof(string)},
{"WebServer:Port", typeof(int)},
{"WebServer:Debug", typeof(bool)},
{"Discord:Prefix", typeof(string)},
{"Discord:Token", typeof(string)},
{"Discord:BaseUri", typeof(string)},
{"Discord:ClientId", typeof(string)},
{"Discord:ClientSecret", typeof(string)},
{"Lodestone:ChaosBotApi:ApiToken", typeof(string)},
{"Lodestone:ChaosBotApi:Url", typeof(string)},
{"Database:Host", typeof(string)},
{"Database:Port", typeof(int)},
{"Database:User", typeof(string)},
{"Database:Pass", typeof(string)},
{"Database:Name", typeof(string)},
};
public Configuration()
{
_appSettingsWrapper = Program.AppSettingsHandler;
if (_appSettingsWrapper == null)
throw new NullReferenceException("Program.AppSettingsHandler is unset");
}
/**
* Gets the configuration value associated with a key in an optional guild
* <exception cref="ArgumentException">Configuration key does not exist</exception>
* <exception cref="ArgumentException">Configuration key does not have the provided type</exception>
* <returns>Configuration value</returns>
*/
public T GetValue<T>(string key, T defaultValue, ulong? guildId = null)
{
if (!ConfigurationFlags.ContainsKey(key))
throw new ArgumentException($"Configuration does not contain key '{key}'");
if (!(ConfigurationFlags[key] == typeof(T)))
throw new ArgumentException($"Configuration flag '{key}<{ConfigurationFlags[key]}>' does not have type '{typeof(T)}'");
if (guildId.HasValue)
return ConfigurationRepository.GetValue(key, guildId.Value, defaultValue);
return _appSettingsWrapper.GetValue(key, defaultValue);
}
public T GetValue<T>(string key)
{
return GetValue<T>(key, default);
}
public IConfigurationSection GetSection(string key)
{
return _appSettingsWrapper.GetSection(key);
}
/**
* Get the available configuration flags
* <returns>Immutable dictionary of config-key/type pairs</returns>
*/
public ImmutableDictionary<string, Type> GetConfigurationFlags()
{
return ConfigurationFlags.ToImmutableDictionary();
}
}
}