using System;
using System.Collections;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace YGNT.Infrastructure.Helper
{
    /// <summary>
    /// appsettings.json操作类
    /// </summary>
    public class AppSettings
    {
        /// <summary>
        /// 配置文件配置
        /// </summary>
        static IConfiguration Configuration { get; set; }
        /// <summary>
        /// 环境变量配置
        /// </summary>
        static IDictionary Dictionary { get; set; }

        static AppSettings()
        {
            //ReloadOnChange = true 当appsettings.json被修改时重新加载
            Configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })//请注意要把当前appsetting.json 文件->右键->属性->复制到输出目录->始终复制
            .Build();

            //读取环境变量里面的配置
            Dictionary = Environment.GetEnvironmentVariables();
        }

        /// <summary>
        /// 得到配置信息
        /// </summary>
        /// <param name="keyTree">key的层集</param>
        /// <returns>对应的value</returns>
        public static string App(params string[] keyTree)
        {
            //优先读取环境变量里面的
            var key = string.Join("_", keyTree).ToUpper();
            var value = Dictionary[key]?.ToString().Replace("\"", "");
            if (!string.IsNullOrEmpty(value))
                return value;

            //在读取配置文件里面的
            key = string.Join(":", keyTree);
            return Configuration[key] ?? string.Empty;
        }
    }
}
