| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- using Common.Global;
- using Database.Database;
- using Microsoft.Identity.Client;
- namespace Esim.Apis.Singleton
- {
- public class ConfigManager
- {
- private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ConfigManager));
- private ModelContext dbContext;
- private List<Config> appConfigs = new List<Config>();
- private ConfigManager()
- {
- dbContext = new DbHelper().GetDbContext(GlobalConfig.Configuration!);
- log.Debug("ConfigManager initialized");
- }
- private static readonly object lockObj = new object();
- private static ConfigManager? instance;
- public static ConfigManager Instance => instance ??= new ConfigManager();
- public void Initialize()
- {
- appConfigs = dbContext.Configs.ToList();
- log.Debug("ConfigManager initialized");
- }
- public string GetConfigWebValue(string configName, string lang = "lo")
- {
- var config = appConfigs.FirstOrDefault(c => c.Name == configName && c.Type == "WEB");
- if (config != null)
- {
- log.Debug($"Config found: {configName} = {config.ValueLocal}");
- return GetValueByLang(config, lang);
- }
- log.Warn($"Config not found: {configName}");
- return string.Empty;
- }
- public string GetConfigSmsValue(string configName, string lang = "lo")
- {
- var config = appConfigs.FirstOrDefault(c => c.Name == configName && c.Type == "SMS");
- if (config != null)
- {
- log.Debug($"Config found: {configName} = {config.ValueLocal}");
- return GetValueByLang(config, lang);
- }
- log.Warn($"Config not found: {configName}");
- return string.Empty;
- }
- public string GetConfigAppValue(string configName, string lang = "lo")
- {
- var config = appConfigs.FirstOrDefault(c => c.Name == configName && c.Type == "APP");
- if (config != null)
- {
- log.Debug($"Config found: {configName} = {config.ValueLocal}");
- return GetValueByLang(config, lang);
- }
- log.Warn($"Config not found: {configName}");
- return string.Empty;
- }
- /// <summary>
- /// Get config value by language: vi=Vietnamese, en=English, lo=Lao (default)
- /// </summary>
- private string GetValueByLang(Config config, string lang)
- {
- return lang switch
- {
- "vi" => config.Value ?? config.ValueLocal ?? "",
- "en" => config.ValueGlobal ?? config.ValueLocal ?? "",
- _ => config.ValueLocal ?? "" // Default: Lao
- };
- }
- // loop 5p to refresh
- public void RefreshConfigs()
- {
- while (true)
- {
- try
- {
- log.Debug($"ConfigManager refreshing...");
- appConfigs = dbContext.Configs.ToList();
- log.Debug("ConfigManager refreshed");
- }
- catch (Exception ex)
- {
- log.Error("Error refreshing configs", ex);
- }
- Thread.Sleep(5 * 60 * 1000); // 5 minutes
- }
- }
- }
- }
|