using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace SyncSDK_Demo
{
    public class IniFile
    {
        private string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

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

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileSectionNames(byte[] lpszReturnBuffer, int nSize, string lpFileName);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileSection(string section, byte[] lpszReturnBuffer, int nSize, string lpFileName);

        public IniFile(string iniPath)
        {
            path = iniPath;
            // 检查文件是否存在，如果不存在则创建
            if (!File.Exists(path))
            {
                using (FileStream fs = File.Create(path))
                {
                    // 可以选择在这里写入一些初始内容，比如默认的节和键值对
                }
            }
        }

        public void WriteValue(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, path);
        }

        public string ReadValue(string section, string key)
        {
            StringBuilder sb = new StringBuilder(255);
            int result = GetPrivateProfileString(section, key, "", sb, 255, path);
            return sb.ToString();
        }
        public List<string> ReadAllValuesInSection(string section)
        {
            List<string> values = new List<string>();
            byte[] buffer = new byte[32768]; // 最大长度
            int bytesRead = GetPrivateProfileSection(section, buffer, buffer.Length, path);

            if (bytesRead > 0)
            {
                string content = Encoding.Default.GetString(buffer, 0, bytesRead - 1);
                Console.WriteLine($"Raw content: {content}"); // 调试输出

                string[] keyValuePairs = content.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string pair in keyValuePairs)
                {
                    if (pair.Contains("="))
                    {
                        string[] parts = pair.Split(new char[] { '=' }, 2);
                        if (parts.Length == 2)
                        {
                            values.Add(parts[1].Trim());
                        }
                    }
                }
            }

            return values;
        }
    }

}