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

namespace ITC81DB
{
    public class IniFile
    {
        [DllImport("KERNEL32.DLL")]
        private static extern bool WritePrivateProfileString(string IpAppName, string IpKeyName, string IpString, string IpFileName);

        [DllImport("KERNEL32.DLL")]
        private static extern uint GetPrivateProfileInt(string IpAppName, string IpKeyName, int nDefault, string IpFileName);

        [DllImport("KERNEL32.DLL")]
        static extern uint GetPrivateProfileString(string IpAppName, string IpKeyName, string IpDefault, StringBuilder IpReturnedString, int nSize, string IpFileName);

        /// <summary>
        /// Ini 파일 읽기
        /// </summary>
        /// <param name="IpAppName">값을 가져올 키가 속해있는 [섹션] 문자열</param>
        /// <param name="IpKeyName">값을 가져올 키</param>
        /// <param name="IpDefault">해당되는 값이 없을 경우, 기본값으로 리턴할 문자열</param>
        /// <param name="filePath">읽어올 ini 파일 경로</param>
        /// <returns>실패 : "" 반환</returns>
        public static string GetIni(String IpAppName, string IpKeyName, string IpDefault, string filePath)
        {
            string ret = "";
            string iniFile = filePath;

            try
            {
                string readString = "";
                string[] stringArray;

                using (StreamReader sr = new StreamReader(filePath, Encoding.Default))
                {
                    readString = sr.ReadToEnd();
                    sr.BaseStream.Position = 0;

                    // Key값이 포함된 Line을 읽을 경우
                    if (readString.Contains(IpKeyName) == true)
                    {
                        int length;
                        string[] text = readString.Split('\n');
                        for (int i = 0; i < text.Length; i++)
                            text[i] = text[i].Trim();

                        for (int i = 0; i < text.Length; i++)
                        {
                            if (text[i].StartsWith(IpKeyName) == true)
                            {
                                stringArray = text[i].Split('=');
                                ret = stringArray[stringArray.Length - 1];

                                break;
                            }
                        }
                        sr.Close();
                    }
                }

                return ret;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// Ini 파일 쓰기
        /// </summary>
        /// <param name="IpAppName">값을 입력할 키가 속해있는 [섹션] 문자열</param>
        /// <param name="IpKeyName">값을 입력할 키</param>
        /// <param name="IpValue">쓸 키 값</param>
        /// <param name="filePath">쓸 ini 파일 경로</param>
        /// <returns>성공 : true, 실패 : false</returns>
        public static Boolean SetIni(string IpAppName, string IpKeyName, string IpValue, string filePath)
        {
            try
            {
                string iniFile = filePath;
                string readString = "";

                using (StreamReader sr = new StreamReader(filePath, Encoding.Default))
                {
                    readString = sr.ReadToEnd();
                    sr.BaseStream.Position = 0;

                    // Key값이 포함된 Line을 읽을 경우
                    if (readString.Contains(IpKeyName) == true)
                    {
                        int length;
                        string[] text = readString.Split('\n');
                        for (int i = 0; i < text.Length; i++)
                            text[i] = text[i].Trim();

                        for (int i = 0; i < text.Length; i++)
                        {
                            if (text[i].StartsWith(IpKeyName) == true)
                            {
                                length = text[i].Length;

                                int offset = readString.IndexOf(IpKeyName, 0);
                                readString = readString.Remove(offset, length);
                                readString = readString.Insert(offset, IpKeyName + "=" + IpValue);

                                break;
                            }
                        }

                        sr.Close();

                        File.Delete(filePath);

                        StreamWriter sw = new StreamWriter(filePath, true, Encoding.Default);

                        sw.Write(readString);
                        sw.Close();

                        return true;
                    }
                }          

                return false;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Ini 파일 생성
        /// </summary>
        /// <param name="programName">Program명(ex. ITC81DB)</param>
        /// <param name="version">Version(ex. 8.0.0)</param>
        /// <param name="releaseDate">릴리즈 날짜(ex. 2022.03.04)</param>
        /// <returns>성공 : true, 실패 : false</returns>
        public static Boolean CreateVersionIni(string programName, string version, string releaseDate)
        {
            try
            {
                string strCheckFolder = "";

                strCheckFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\";
                strCheckFolder += "Version.ini";
                if (File.Exists(strCheckFolder) == false)
                {
                    using (StreamWriter sw = new StreamWriter(strCheckFolder, true, Encoding.Default))
                    {
                        sw.Write("[PROGRAMINFO]" + "\r\n");
                        sw.Write("NAME=" + programName + "\r\n");
                        sw.Write("VERSION=" + version + "\r\n");
                        sw.Write("RELEASE=" + releaseDate + "\r\n");
                    }
                }
            }
            catch
            {
                return false;
            }

            return true;
        }
    }
}
