using System;
using System.Management;
using System.Text;

namespace LevelCode.License.Security
{
    public static class HwidService
    {
        // =========================
        // GERAR HWID BRUTO
        // =========================
        public static string GerarHwid()
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                sb.Append(GetCpuId());
                sb.Append("|");
                sb.Append(GetDiskSerial());
                sb.Append("|");
                sb.Append(Environment.MachineName);
            }
            catch
            {
                sb.Append(Environment.MachineName);
            }

            return sb.ToString();
        }

        // =========================
        // CPU ID
        // =========================
        private static string GetCpuId()
        {
            try
            {
                using (ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor"))
                {
                    foreach (ManagementObject obj in searcher.Get())
                    {
                        return obj["ProcessorId"]?.ToString();
                    }
                }
            }
            catch { }

            return "CPU_UNKNOWN";
        }

        // =========================
        // DISK SERIAL
        // =========================
        private static string GetDiskSerial()
        {
            try
            {
                using (ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_PhysicalMedia"))
                {
                    foreach (ManagementObject obj in searcher.Get())
                    {
                        if (obj["SerialNumber"] != null)
                            return obj["SerialNumber"].ToString().Trim();
                    }
                }
            }
            catch { }

            return "DISK_UNKNOWN";
        }
    }
}
