using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CCDCount.DLL
{
    public class IniFileClass
    {
        [DllImport("kernel32", CharSet = CharSet.Auto)]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32", CharSet = CharSet.Auto)]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        // 通用写入方法
        public static void WriteIni<T>(T config, string filePath, string section = "Config")
        {
            foreach (PropertyInfo prop in typeof(T).GetProperties())
            {
                object value = prop.GetValue(config);
                WritePrivateProfileString(section, prop.Name, value?.ToString() ?? "", filePath);
            }
        }

        // 通用读取方法
        public static void ReadIni<T>(ref T config, string filePath, string section = "Config")
        {
            foreach (var prop in typeof(T).GetProperties())
            {
                var sb = new StringBuilder(255);
                GetPrivateProfileString(section, prop.Name, "", sb, 255, filePath);

                if (string.IsNullOrEmpty(sb.ToString())) continue;

                try
                {
                    var value = Convert.ChangeType(sb.ToString(), prop.PropertyType);
                    prop.SetValue(config, value, null);
                }
                catch (InvalidCastException)
                {
                    // 处理类型转换失败（可扩展日志记录）
                }
            }
        }
    }
}
