using Microsoft.Win32;
using Sonex.Data.Database;
using System;

namespace Sonex.Client.Dialogs
{
    public static class AppSessionInfo
    {
        private const string CurrentVersionRegistryKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";

        public static string ApplicationName => "SonexClient";
        public static string ApplicationVersion => AppInfo.InformationalVersion.Trim();
        public static string InstanceId { get; } = Guid.NewGuid().ToString("N")[..8].ToUpperInvariant();
        public static string OsVersionNumber { get; } = Environment.OSVersion.Version.ToString();
        public static string? OsProductName { get; } = ReadCurrentVersionValue("ProductName");
        public static string? OsDisplayVersion { get; } =
            ReadCurrentVersionValue("DisplayVersion")
            ?? ReadCurrentVersionValue("ReleaseId");
        public static string OsVersion => $"win-{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor}.{Environment.OSVersion.Version.Build}";

        public static DbClientSessionInfo CreateDbClientSessionInfo()
        {
            return new DbClientSessionInfo
            {
                ApplicationName = ApplicationName,
                ApplicationVersion = ApplicationVersion,
                InstanceId = InstanceId,
                OsVersion = OsVersion,
                OsVersionNumber = OsVersionNumber,
                OsProductName = OsProductName,
                OsDisplayVersion = OsDisplayVersion
            };
        }

        private static string? ReadCurrentVersionValue(string valueName)
        {
            try
            {
                using var key = Registry.LocalMachine.OpenSubKey(CurrentVersionRegistryKey);
                return key?.GetValue(valueName)?.ToString()?.Trim();
            }
            catch
            {
                return null;
            }
        }
    }
}
