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

namespace PDFReader_Demo_CSharp.Common
{
    class IniFileHelper
    {
        [DllImport("kernel32")]  // Return value: 0 means failure, while non-zero means success.
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        [DllImport("kernel32")]  // Return value: the length of string buffer
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);

        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(2048);
                long operState = GetPrivateProfileString(Section, Key, NoText, temp, 2048, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
                if (OpStation == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
    }

    class NormalFileHelper
    {
        public static string GetKeyValue(string Key, string filePath)
        {
            FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate);
            StreamReader streamReader = new StreamReader(fileStream);

            Dictionary<string, string> dic = new Dictionary<string, string>();  
            while (streamReader.Peek() >= 0)
            {
                var str = streamReader.ReadLine();
                if (str == null || str.Length == 0) continue;
                int charIndex = str.IndexOf('=');
                if (charIndex != -1)
                {
                    var key = str.Substring(0, charIndex);
                    var value = str.Substring(charIndex+1);

                    dic.Add(key, value);
                }
            }
            streamReader.Close();

            return dic.FirstOrDefault(x => x.Key == Key).Value;
        }
    }
}
