using System;
using System.Management;
using System.Runtime.InteropServices;
using System.Windows;
using Microsoft.VisualBasic.Devices;
using Newtonsoft.Json;

namespace Valg.EVA.Skanning.Diagnostics
{
    public static class SystemInformationCollector
    {
        
        
        
        public static void CollectAndReportSystemInformation()
        {
            try
            {
                var systemInformation = CollectSystemInformation();
                EvaSkanningEventSource.Log.SystemInformationCollected(JsonConvert.SerializeObject(systemInformation));
            }
            catch (Exception e)
            {
                
                EvaSkanningEventSource.Log.SystemInformationCollectionFailed(e.ToString());
            }
        }

        
        
        
        
        public static SystemInformation CollectSystemInformation()
        {
            var computerInfo = new ComputerInfo();

            var info = new SystemInformation
            {
                MachineName = Environment.MachineName,
                FrameworkDescription = RuntimeInformation.FrameworkDescription,
                OSDescription = Environment.OSVersion.ToString(),
                OSArchitecture = Environment.Is64BitOperatingSystem ? "x64" : "x86",
                ProcessorCount = Environment.ProcessorCount,
                ProcessorName = GetProcessorName(),
                AvailablePhysicalMemoryInGB = Math.Round(computerInfo.AvailablePhysicalMemory / 1024d / 1024d / 1024d, 2),
                TotalPhysicalMemoryInGB = Math.Round(computerInfo.TotalPhysicalMemory / 1024d / 1024d / 1024d, 2),
                ScreenSize = SystemParameters.PrimaryScreenWidth + "x" + SystemParameters.PrimaryScreenHeight,
                CollectedAtTimestamp = DateTime.Now.ToString("s")
            };

            return info;
        }

        
        
        
        
        private static string GetProcessorName()
        {
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor"))
            {
                foreach (var o in searcher.Get())
                {
                    var queryObj = (ManagementObject)o;
                    return queryObj["Name"].ToString();
                }
            }

            return string.Empty;
        }
    }
}
