using ProjectManagementSystem.Common.Log;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectManagementSystem.Common.Function
{
    public class AppSetting
    {
        private static string m_configurationFilePath;
        private static Configuration m_configuration;

        static AppSetting()
        {
            string s = System.Reflection.Assembly.GetExecutingAssembly().Location;
            System.IO.FileInfo finfo = new System.IO.FileInfo(s);
            string currPath = finfo.DirectoryName;

            m_configurationFilePath = System.IO.Path.Combine(currPath, "ProjectManagementSystem.exe");
            m_configuration = ConfigurationManager.OpenExeConfiguration(m_configurationFilePath);
        }

        public static string GetPmsApiUrl(string apiName)
        {
            return $"{GetString("PmsApi")}{apiName}";
        }

        public static string GetString(string key)
        {
            return TryGetValueFromConfig((value) => value, () => string.Empty, key);
        }

        public static bool GetBool(string key)
        {
            return TryGetValueFromConfig((value) => bool.Parse(value), () => false, key);
        }

        public static int GetInt(string key)
        {
            return TryGetValueFromConfig((value) => int.Parse(value), () => 0, key);
        }

        private static T TryGetValueFromConfig<T>(Func<string, T> parseFunc, Func<T> defaultTValueFunc, string key)
        {
            T result;
            try
            {
                string value = m_configuration.AppSettings.Settings[key].Value;
                result = ((!string.IsNullOrEmpty(value)) ? parseFunc(value) : defaultTValueFunc());
            }
            catch (Exception ex)
            {
                CLog.Instance.GetLog("System").WriteException("Exception", "读取配置时产生异常", ex);
                result = defaultTValueFunc();
            }
            return result;
        }
    }
}

