using Microsoft.IdentityModel.Logging;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace EasyTemplate.Tool;

public class Computer
{
    public static ComputerInfo GetComputerInfo()
    {
        ComputerInfo computerInfo = new ComputerInfo();
        try
        {
            MemoryMetricsClient client = new MemoryMetricsClient();
            MemoryMetrics memoryMetrics = client.GetMetrics();
            computerInfo.RAMUsage = Math.Ceiling(memoryMetrics.Used / 1024).ToString() + " GB / " + Math.Ceiling(memoryMetrics.Total / 1024).ToString() + " GB";

            var rate = Math.Ceiling(100 * memoryMetrics.Used / memoryMetrics.Total);
            computerInfo.RAMUsageRate = rate.ToString() + "%";
            switch (rate)
            {
                default: computerInfo.RAMStatus = ComputerStatus.Normal; break;
                case >= 85: computerInfo.RAMStatus = ComputerStatus.Error; break;
                case >= 75 and < 90: computerInfo.RAMStatus = ComputerStatus.Warning; break;
            }

            computerInfo.CPURate = Math.Ceiling(GetCPURate().ToDouble()).ToString();
            computerInfo.RunTime = GetRunTime();
        }
        catch (Exception ex)
        {
            Log.Error(ex);
        }

        try
        {
            // 获取系统盘（通常是C盘）
            var systemDrive = new DriveInfo("C");
            if (systemDrive.IsReady)
            {
                // 总空间（字节）
                long totalSpace = systemDrive.TotalSize;
                // 可用空间（字节）
                long freeSpace = systemDrive.AvailableFreeSpace;
                // 已用空间（字节）
                long usedSpace = totalSpace - freeSpace;

                // 转换为GB
                double totalSpaceGB = Math.Round(totalSpace / 1024.0 / 1024 / 1024, 2);
                double freeSpaceGB = Math.Round(freeSpace / 1024.0 / 1024 / 1024, 2);
                double usedSpaceGB = Math.Round(usedSpace / 1024.0 / 1024 / 1024, 2);

                // 使用率
                double usagePercentage = Math.Round((double)usedSpace / totalSpace * 100, 2);
                switch (usagePercentage)
                {
                    default: computerInfo.SystemDiskStatus = ComputerStatus.Normal; break;
                    case >= 85: computerInfo.SystemDiskStatus = ComputerStatus.Error; break;
                    case >= 75 and < 90: computerInfo.SystemDiskStatus = ComputerStatus.Warning; break;
                }

                computerInfo.SystemDiskUsage = $"{usedSpaceGB} GB / {totalSpaceGB} GB";
                computerInfo.SystemDiskUsageRate = $"{usagePercentage}%";
            }
        }
        catch (Exception ex)
        {

        }

        return computerInfo;
    }

    public static bool IsUnix()
    {
        var isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
        return isUnix;
    }

    public static string GetCPURate()
    {
        string cpuRate = string.Empty;
        if (IsUnix())
        {
            string output = ShellCmd.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
            cpuRate = output.Trim();
        }
        else
        {
            string output = ShellCmd.Cmd("wmic", "cpu get LoadPercentage");
            cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
        }
        return cpuRate;
    }

    public static string GetRunTime()
    {
        string runTime = string.Empty;
        try
        {
            if (IsUnix())
            {
                string output = ShellCmd.Bash("uptime -s");
                output = output.Trim();
                runTime = Extension.FormatTime((DateTime.Now - output.ToDate()).TotalMilliseconds.ToString().Split('.')[0].ToLong());
            }
            else
            {
                string output = ShellCmd.Cmd("wmic", "OS get LastBootUpTime/Value");
                string[] outputArr = output.Split("=", StringSplitOptions.RemoveEmptyEntries);
                if (outputArr.Length == 2)
                {
                    runTime = Extension.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ToDate()).TotalMilliseconds.ToString().Split('.')[0].ToLong());
                }
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex);
        }
        return runTime;
    }
}

public class MemoryMetricsClient
{
    public MemoryMetrics GetMetrics()
    {
        if (Computer.IsUnix())
        {
            return GetUnixMetrics();
        }
        return GetWindowsMetrics();
    }

    private MemoryMetrics GetWindowsMetrics()
    {
        string output = ShellCmd.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");

        var lines = output.Trim().Split("\n");
        var freeMemoryParts = lines[0].Split("=", StringSplitOptions.RemoveEmptyEntries);
        var totalMemoryParts = lines[1].Split("=", StringSplitOptions.RemoveEmptyEntries);

        var metrics = new MemoryMetrics();
        metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
        metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);
        metrics.Used = metrics.Total - metrics.Free;

        return metrics;
    }

    private MemoryMetrics GetUnixMetrics()
    {
        string output = ShellCmd.Bash("free -m");

        var lines = output.Split("\n");
        var memory = lines[1].Split(" ", StringSplitOptions.RemoveEmptyEntries);

        var metrics = new MemoryMetrics();
        metrics.Total = double.Parse(memory[1]);
        metrics.Used = double.Parse(memory[2]);
        metrics.Free = double.Parse(memory[3]);

        return metrics;
    }
}

public class MemoryMetrics
{
    public double Total { get; set; }
    public double Used { get; set; }
    public double Free { get; set; }
}

public enum ComputerStatus
{
    Normal,
    Error,
    Warning
}

public class ComputerInfo
{
    /// <summary>
    /// CPU使用率
    /// </summary>
    public string CPURate { get; set; }
    /// <summary>
    /// 总内存
    /// </summary>
    public string RAMUsage { get; set; }
    /// <summary>
    /// 内存使用率
    /// </summary>
    public string RAMUsageRate { get; set; }
    /// <summary>
    /// 内存状态
    /// </summary>
    public ComputerStatus RAMStatus { get; set; }
    /// <summary>
    /// 系统运行时间
    /// </summary>
    public string RunTime { get; set; }
    /// <summary>
    /// 系统盘用量
    /// </summary>
    public string SystemDiskUsage { get; set; }
    /// <summary>
    /// 系统盘使用率
    /// </summary>
    public string SystemDiskUsageRate { get; set; }
    /// <summary>
    /// 系统盘状态
    /// </summary>
    public ComputerStatus SystemDiskStatus { get; set; }
}