using System;
using System.Configuration;
using System.Globalization;
using System.Reflection;

namespace FSI.Lib
{
    public static class Settings
    {
        //static UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
#if NET472
        static UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().Location);                                                                                       
#elif NET6_0
        static UriBuilder uri = new(Assembly.GetExecutingAssembly().Location);
#endif

        static readonly NumberFormatInfo nfi = new NumberFormatInfo()
        {
            NumberGroupSeparator = "",
            CurrencyDecimalSeparator = "."
        };

        public static T Setting<T>(string name)
        {
            return Setting<T>(name, Mode.DllSettings);
        }

        public static T Setting<T>(string name, Mode exeSettings)
        {
            if (exeSettings == Mode.ExeSetttings)
            {
                Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");

                return (T)Convert.ChangeType(appSettingsSection.Settings[name].Value, typeof(T), nfi);
            }

            if (exeSettings == Mode.DllSettings)
            {
                Configuration configuration = ConfigurationManager.OpenExeConfiguration(uri.Path);
                AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
                return (T)Convert.ChangeType(appSettingsSection.Settings[name].Value, typeof(T), nfi);
            }

            return (T)Convert.ChangeType(null, typeof(T), nfi);
        }

        public enum Mode
        {
            ExeSetttings,
            DllSettings,
        }
    }
}


/*

App.Config file sample

    <add key="Enabled" value="true" />
    <add key="ExportPath" value="c:\" />
    <add key="Seconds" value="25" />
    <add key="Ratio" value="0.14" />

Usage:

  somebooleanvar = Settings.Setting<bool>("Enabled");
  somestringlvar = Settings.Setting<string>("ExportPath");
  someintvar =     Settings.Setting<int>("Seconds");
  somedoublevar =  Settings.Setting<double>("Ratio");

*/