using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CallCenter.Utility
{
    public class SysInformationHelper
    {
        private int m_ProcessorCount = 0;   //CPU个数   
        private PerformanceCounter pcCpuLoad;   //CPU计数器   
        private float m_PhysicalMemory = 0;   //物理内存   

        private const int GW_HWNDFIRST = 0;
        private const int GW_HWNDNEXT = 2;
        private const int GWL_STYLE = (-16);
        private const int WS_VISIBLE = 268435456;
        private const int WS_BORDER = 8388608;

        #region AIP声明   
        [DllImport("IpHlpApi.dll")]
        extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);

        [DllImport("User32")]
        private extern static int GetWindow(int hWnd, int wCmd);

        [DllImport("User32")]
        private extern static int GetWindowLongA(int hWnd, int wIndx);

        [DllImport("user32.dll")]
        private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);

        [DllImport("user32", CharSet = CharSet.Auto)]
        private extern static int GetWindowTextLength(IntPtr hWnd);

        #endregion
        // 构造函数，初始化计数器等   
        public SysInformationHelper()
        {
            //初始化CPU计数器   
            pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            pcCpuLoad.MachineName = ".";
            pcCpuLoad.NextValue();
            System.Threading.Thread.Sleep(1000);    // wait for 1 second 

            //CPU个数   
            m_ProcessorCount = Environment.ProcessorCount;

            //获得物理内存   
            ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (mo["TotalPhysicalMemory"] != null)
                {
                    m_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
                }
            }
        }

        #region CPU个数   
        // 获取CPU个数     
        public int ProcessorCount
        {
            get
            {
                return m_ProcessorCount;
            }
        }
        #endregion

        #region CPU占用率   
        // 获取CPU占用率    
        public float CpuLoad
        {
            get
            {
                return pcCpuLoad.NextValue();
            }
        }
        #endregion

        #region 可用内存/物理内存  
        // 获取可用内存(RAM)  
        public float MemoryAvailable
        {
            get
            {
                float availablebytes = 0;
                ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
                foreach (ManagementObject mo in mos.GetInstances())
                {
                    if (mo["FreePhysicalMemory"] != null)
                    {
                        availablebytes = 1024 * float.Parse(mo["FreePhysicalMemory"].ToString());
                    }
                }
                return availablebytes;
            }
        }

        // 获取物理内存(RAM)  
        public float PhysicalMemory
        {
            get
            {
                return m_PhysicalMemory;
            }
        }
        #endregion

        /// <summary>
        /// 硬盘使用百分比
        /// </summary>
        /// <param name="HardDisc"></param>
        /// <returns></returns>
        public float GetDrivePer1(string HardDisc)
        {
            System.IO.DriveInfo[] drives = System.IO.Directory.GetLogicalDrives().Select(q => new System.IO.DriveInfo(q)).ToArray();
            float ret = 0;
            double total = 0, ones = 0;
            HardDisc = HardDisc + ":\\";
            foreach (var driveInfo in drives)
            {
                if (driveInfo.IsReady && driveInfo.Name == HardDisc)
                {
                    ones = ConverDiskSpace(driveInfo.TotalSize) - ConverDiskSpace(driveInfo.TotalFreeSpace);
                    total = ConverDiskSpace(driveInfo.TotalSize);
                }
            }
            if (ones > 0 && total > 0)
            {
                ret = (float)((ones * 100) / total);
            }
            return ret;
        }

        /// <summary>
        /// 磁盘大小换算
        /// </summary>
        /// <param name="bytesNumber"></param>
        /// <returns></returns>
        public static double ConverDiskSpace(long bytesNumber)
        {
            long value = 0;
            double ret = 0;
            if (((value = (long)(((bytesNumber / (1024 * 1024 * 1024)) * (1.0 / 1024)))) >= 1))
            {
                ret = (double)(bytesNumber / (1024 * 1024 * 1024)) * (1.0 / 1024);
            }
            else if ((value = bytesNumber / (1024 * 1024 * 1024)) >= 1)
            {
                ret = (double)bytesNumber / (1024 * 1024 * 1024);
            }
            else if ((value = bytesNumber / (1024 * 1024)) >= 1)
            {
                ret = (double)bytesNumber / (1024 * 1024);
            }
            else if ((value = bytesNumber / (1024)) >= 1)
            {
                ret = (double)bytesNumber / (1024);
            }
            else
            {
                ret = (double)bytesNumber;
            }
            return ret;
        }

        #region 计算机的唯一标识代码
        /// <summary>
        /// 16字节的计算机的唯一标识代码
        /// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
        /// </summary>
        /// <returns></returns>
        public static string GetPCUniqueIdentificationCode()
        {
            string fingerPrint = string.Empty;
            if (string.IsNullOrEmpty(fingerPrint))
            {
                fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " +
                        biosId() + "\nBASE >> " + baseId() +
                        videoId() + "\nMAC >> " + macId()
                        );
                //+"\nDISK >> "+ diskId() + "\nVIDEO >> " + 
            }
            return fingerPrint;
        }

        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }
        private static string GetHexString(byte[] bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + (int)'A')).ToString();
                else
                    s += n2.ToString();
                if (n1 > 9)
                    s += ((char)(n1 - 10 + (int)'A')).ToString();
                else
                    s += n1.ToString();
                if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }
        #region Original Device ID Getting Code
        //Return a hardware identifier
        private static string identifier
        (string wmiClass, string wmiProperty, string wmiMustBeTrue)
        {
            string result = "";
            System.Management.ManagementClass mc =
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                if (mo[wmiMustBeTrue].ToString() == "True")
                {
                    //Only get the first one
                    if (result == "")
                    {
                        try
                        {
                            result = mo[wmiProperty].ToString();
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return result;
        }
        //Return a hardware identifier
        private static string identifier(string wmiClass, string wmiProperty)
        {
            string result = "";
            System.Management.ManagementClass mc =
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "")
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch
                    {
                    }
                }
            }
            return result;
        }
        private static string cpuId()
        {
            //Uses first CPU identifier available in order of preference
            //Don't get all identifiers, as it is very time consuming
            string retVal = identifier("Win32_Processor", "UniqueId");
            if (retVal == "") //If no UniqueID, use ProcessorID
            {
                retVal = identifier("Win32_Processor", "ProcessorId");
                if (retVal == "") //If no ProcessorId, use Name
                {
                    retVal = identifier("Win32_Processor", "Name");
                    if (retVal == "") //If no Name, use Manufacturer
                    {
                        retVal = identifier("Win32_Processor", "Manufacturer");
                    }
                    //Add clock speed for extra security
                    retVal += identifier("Win32_Processor", "MaxClockSpeed");
                }
            }
            return retVal;
        }
        //BIOS Identifier
        private static string biosId()
        {
            return identifier("Win32_BIOS", "Manufacturer")
            + identifier("Win32_BIOS", "SMBIOSBIOSVersion")
            + identifier("Win32_BIOS", "IdentificationCode")
            + identifier("Win32_BIOS", "SerialNumber")
            + identifier("Win32_BIOS", "ReleaseDate")
            + identifier("Win32_BIOS", "Version");
        }
        //Main physical hard drive ID
        private static string diskId()
        {
            return identifier("Win32_DiskDrive", "Model")
            + identifier("Win32_DiskDrive", "Manufacturer")
            + identifier("Win32_DiskDrive", "Signature")
            + identifier("Win32_DiskDrive", "TotalHeads");
        }
        //Motherboard ID
        private static string baseId()
        {
            return identifier("Win32_BaseBoard", "Model")
            + identifier("Win32_BaseBoard", "Manufacturer")
            + identifier("Win32_BaseBoard", "Name")
            + identifier("Win32_BaseBoard", "SerialNumber");
        }
        //Primary video controller ID
        private static string videoId()
        {
            return identifier("Win32_VideoController", "DriverVersion")
            + identifier("Win32_VideoController", "Name");
        }
        //First enabled network card ID
        private static string macId()
        {
            return identifier("Win32_NetworkAdapterConfiguration",
                "MACAddress", "IPEnabled");
        }
        #endregion
        #endregion
    }
}
