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

namespace Pilz.Cryptography
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class Helpers
    {
        private static string clientSecret = null;

        public static string CalculateClientSecret()
        {
            // Try getting serial number of C drive
            if (clientSecret == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                ManagementObjectSearcher searcher = new("SELECT * FROM Win32_PhysicalMedia");
                string sn = null;

                foreach (var entry in searcher.Get())
                {
                    if (entry is ManagementObject wmi_HD && string.IsNullOrEmpty(sn) && wmi_HD["SerialNumber"] != null)
                        sn = wmi_HD["SerialNumber"].ToString()?.Trim();
                }

                clientSecret = sn;
            }

            // Fallback to Mashine name
            clientSecret ??= Environment.MachineName;

            return clientSecret;
        }

        public static string GenerateUniquieID<T>(string var)
        {
            var sn = CalculateClientSecret();
            var dateTime = DateTime.UtcNow.ToString("yyyyMMddHHmmssfffffff");
            var type = typeof(T).ToString();
            var together = sn + dateTime + type + var;

            var md5 = MD5.Create();
            var hash = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(together))).Replace("-", string.Empty);
            md5.Dispose();

            return hash;
        }
    }
}
