using System;
using System.Globalization;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;

namespace Crysome.Client.SystemInfo;

public class SystemInformation
{
	private struct OSVERSIONINFOEX
	{
		public uint dwOSVersionInfoSize;

		public uint dwMajorVersion;

		public uint dwMinorVersion;

		public uint dwBuildNumber;

		public uint dwPlatformId;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string szCSDVersion;

		public ushort wServicePackMajor;

		public ushort wServicePackMinor;

		public ushort wSuiteMask;

		public byte wProductType;

		public byte wReserved;
	}

	public string UserName { get; set; }

	public string ComputerName { get; set; }

	public string OperatingSystem { get; set; }

	public string ActiveWindowTitle { get; set; }

	public string Uptime { get; set; }

	public string CountryCode { get; set; }

	public string GPU { get; set; }

	[DllImport("user32.dll")]
	private static extern IntPtr GetForegroundWindow();

	[DllImport("user32.dll", CharSet = CharSet.Unicode)]
	private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

	[DllImport("ntdll.dll")]
	private static extern int RtlGetVersion(ref OSVERSIONINFOEX versionInfo);

	public static SystemInformation Get()
	{
		return new SystemInformation
		{
			UserName = Environment.UserName,
			ComputerName = Environment.MachineName,
			OperatingSystem = GetOSVersion(),
			ActiveWindowTitle = GetActiveWindow(),
			Uptime = GetUptime(),
			CountryCode = GetCountryCode(),
			GPU = GetGPU()
		};
	}

	private static string GetGPU()
	{
		try
		{
			using ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
			using ManagementObjectCollection.ManagementObjectEnumerator managementObjectEnumerator = managementObjectSearcher.Get().GetEnumerator();
			if (managementObjectEnumerator.MoveNext())
			{
				return ((ManagementObject)managementObjectEnumerator.Current)["Name"]?.ToString() ?? "N/A";
			}
		}
		catch
		{
		}
		return "N/A";
	}

	private static string GetActiveWindow()
	{
		try
		{
			IntPtr foregroundWindow = GetForegroundWindow();
			if (foregroundWindow == IntPtr.Zero)
			{
				return "N/A";
			}
			StringBuilder stringBuilder = new StringBuilder(256);
			GetWindowText(foregroundWindow, stringBuilder, 256);
			string text = stringBuilder.ToString();
			return string.IsNullOrEmpty(text) ? "N/A" : text;
		}
		catch
		{
			return "N/A";
		}
	}

	private static string GetUptime()
	{
		try
		{
			TimeSpan timeSpan = TimeSpan.FromMilliseconds(Environment.TickCount & 0x7FFFFFFF);
			return $"{(int)timeSpan.TotalDays}d {timeSpan.Hours}h {timeSpan.Minutes}m {timeSpan.Seconds}s";
		}
		catch
		{
			return "N/A";
		}
	}

	private static string GetCountryCode()
	{
		try
		{
			return RegionInfo.CurrentRegion.TwoLetterISORegionName;
		}
		catch
		{
			return "US";
		}
	}

	private static string GetOSVersion()
	{
		try
		{
			OSVERSIONINFOEX versionInfo = new OSVERSIONINFOEX
			{
				dwOSVersionInfoSize = (uint)Marshal.SizeOf(typeof(OSVERSIONINFOEX))
			};
			if (RtlGetVersion(ref versionInfo) == 0)
			{
				string text = BuildToOSName(versionInfo.dwBuildNumber);
				if (!string.IsNullOrEmpty(text))
				{
					string displayVersion = GetDisplayVersion();
					if (!string.IsNullOrEmpty(displayVersion))
					{
						text = text + " " + displayVersion;
					}
					return text;
				}
			}
		}
		catch
		{
		}
		try
		{
			using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
			if (registryKey != null)
			{
				string text2 = registryKey.GetValue("ProductName", "")?.ToString() ?? "";
				if (int.TryParse(registryKey.GetValue("CurrentBuildNumber", "")?.ToString() ?? "", out var result) && result >= 22000 && text2.Contains("Windows 10"))
				{
					text2 = text2.Replace("Windows 10", "Windows 11");
				}
				if (!string.IsNullOrEmpty(text2))
				{
					return text2;
				}
			}
		}
		catch
		{
		}
		return "Windows";
	}

	private static string GetDisplayVersion()
	{
		try
		{
			using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
			return registryKey?.GetValue("DisplayVersion", "")?.ToString() ?? "";
		}
		catch
		{
			return "";
		}
	}

	private static string BuildToOSName(uint build)
	{
		if (build >= 22000)
		{
			return "Windows 11";
		}
		if (build >= 10240)
		{
			return "Windows 10";
		}
		if (build >= 9600)
		{
			return "Windows 8.1";
		}
		if (build >= 9200)
		{
			return "Windows 8";
		}
		if (build >= 7600)
		{
			return "Windows 7";
		}
		if (build >= 6000)
		{
			return "Windows Vista";
		}
		if (build >= 2600)
		{
			return "Windows XP";
		}
		return "";
	}
}
