using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.Framework.Core
{
    /// <summary>
    /// 系统监视解释器 -- GPU
    /// </summary>
    public class SystemMonitorProvider_GPU : IMonitorProvider
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name => "GPU";

        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="info">监控信息</param>
        public void Execute(MonitorInfolBase info)
        {
            SystemMonitorInfo system = info as SystemMonitorInfo;

            try
            {
                NvAPIWrapper.NVIDIA.Initialize();

                var gpus = NvAPIWrapper.GPU.PhysicalGPU.GetPhysicalGPUs();

                for (int i = 0; i < gpus.Length; i++)
                {
                    SystemMonitorGpuInfo item = system.GpuInfos.FirstOrDefault(p => p.Physics == i);
                    if (item == null)
                    {
                        item = new SystemMonitorGpuInfo();
                        item.Physics = i;
                        item.Name = gpus[i].FullName;
                        system.GpuInfos.Add(item);
                    }
                    item.UsedPercentage = gpus[i].UsageInformation.GPU.Percentage / 100d;
                }
            }
            catch
            {
                // 无需处理异常
            }
            finally
            {
                NvAPIWrapper.NVIDIA.Unload();
            }
        }
    }
}
