using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Collections;
using ChuPiao.Common.HD;

namespace ChuPiao.Common.HD
{
    public class HD
    {

        public static string StartupPath = Application.StartupPath;

        // Do this when you start your application
        static int mainThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;


        // If called in the non main thread, will return false;
        public static bool IsMainThread
        {
            get { return System.Threading.Thread.CurrentThread.ManagedThreadId == mainThreadId; }
        }


     

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);


        [DllImport("kernel32")]
        private static extern int WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);


        //读取ini文件 section表示ini文件中的节点名，key表示键名 def没有查到的话返回的默认值 filePath文件路径
        public static string Ini_Read(string section, string key, string def, string filePath)
        {
            return Ini_ReadPBuffSize(section, key, def, filePath, 1024);
        }


        public static int Ini_ReadPInt(string section, string key, int def, string filePath)
        {
            return HD.Convert_Str2Int(HD.Ini_ReadP(section, key, def + "", filePath), def);
        }



        //读取ini文件，如果值为空，写入配置文件默认数值
        public static string Ini_ReadP(string section, string key, string def, string filePath)
        {
             string str=Ini_Read(section,key,"",filePath);
             if (str == "")
             {
                 Ini_Write(section, key, def, filePath);
                 str = def;
             }
             return str;
        }


        public static string Ini_ReadPBuffSize(string section, string key, string def, string filePath, int buffsize)
        {
            StringBuilder sb = new StringBuilder(buffsize);
            GetPrivateProfileString(section, key, def, sb, buffsize, filePath);
            return sb.ToString();
        }


        //写如ini文件 section表示ini文件中的节点名，key表示键名 value写入的值 filePath文件路径
        public static int Ini_Write(string section, string key, object value, string filePath)
        {
            //CheckPath(filePath);
            string str = value == null ? null : value.ToString();
            return WritePrivateProfileString(section, key, str, filePath);
        }


        //删除section 
        public static int Ini_DeleteSection(string section, string filePath)
        {
            return Ini_Write(section, null, null, filePath);
        }


        //删除键
        public static int Ini_DeleteKey(string section, string key, string filePath)
        {
            return Ini_Write(section, key, null, filePath);
        }




        public static void IO_Dispose(params IDisposable[] closes)
        {
            if (closes != null && closes.Length > 0)
            {
                foreach (IDisposable close in closes)
                {
                    close.Dispose();
                }
            }
        }


        public static int Convert_Str2Int(string str,int def) {
            try
            {
                return int.Parse(str);
            }
            catch (Exception e) {
            }
            return def;
        }


        public static int Math_GetRandomNum(int minVar, int maxVar)
        {
            int bound = maxVar - minVar + 1;
            return minVar + new Random().Next(bound);
        }


        /// <summary>
        /// 提取异常及其内部异常堆栈跟踪
        /// </summary>
        /// <param name="exception">提取的例外</param>
        /// <param name="lastStackTrace">最后提取的堆栈跟踪（对于递归）， String.Empty or null</param>
        /// <param name="exCount">提取的堆栈数（对于递归）</param>
        /// <returns>Syste.String</returns>
        public static string Test_ExtractAllStackTrace(Exception exception, string lastStackTrace = null, int exCount = 1)
        {
            var ex = exception;
            const string entryFormat = "#{0}: {1}\r\n{2}";
            //修复最后一个堆栈跟踪参数
            lastStackTrace = lastStackTrace ?? string.Empty;
            //添加异常的堆栈跟踪
            lastStackTrace += string.Format(entryFormat, exCount, ex.Message, ex.StackTrace);
            if (exception.Data.Count > 0)
            {
                lastStackTrace += "\r\n    Data: ";
                foreach (var item in exception.Data)
                {
                    var entry = (DictionaryEntry)item;
                    lastStackTrace += string.Format("\r\n\t{0}: {1}", entry.Key, exception.Data[entry.Key]);
                }
            }
            //递归添加内部异常
            //if ((ex = ex.InnerException) != null)
            //    return ex.Test_ExtractAllStackTrace(string.Format("{0}\r\n\r\n", lastStackTrace), ++exCount);
            return lastStackTrace;
        }


        public static void Test_LogPrint(object obj)
        {

#if DEBUG
            Test_LogPrint("tag", obj);
#endif
        }





        public static void Test_LogPrint(string tag, object obj)
        {
            if (obj == null || "".Equals(obj))
            {
                obj = "空对象";
            }
            if (obj is int || obj is string || obj is bool || obj is Exception)
            {
                System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "-" + tag + " -------- " + obj.ToString()+"\r\n");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "-" + tag + " -------- " + Str_ToJSONString(obj) + "\r\n");
            }
        }


        public static string Str_ToJSONString(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public static bool Str_isEmpty(string text)
        {
            return null == text || text.Length == 0;
        }

        public static string Str_GetOne(string data, string start, string end = null)
        {
            if (Str_isEmpty(data))
            {
                return "";
            }
            if (start == null)
            {
                start = "";
            }

            int startIndex = data.IndexOf(start);
            if (startIndex == -1)
            {
                return "";
            }
            int aa = startIndex + start.Length;
            if (Str_isEmpty(end))
            {
                return data.Substring(aa);
            }
            int endIndex = data.IndexOf(end, aa);
            if (endIndex == -1)
            {
                return "";
            }
            int bb = endIndex - aa;
            return data.Substring(aa, bb);
        }
    }
}
