using System.Diagnostics;
using bitforum.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Runtime.InteropServices;
using System.Management;

namespace bitforum.Controllers.Setting
{
    [Authorize]
    [Route("Setting")]
    public class ServerController : Controller
    {
        private readonly ILogger<ServerController> _logger;
        private readonly IHostEnvironment _env;

        public ServerController(ILogger<ServerController> logger, IHostEnvironment env)
        {
            _logger = logger;
            _env = env;
        }

        [HttpGet("Server")]
        public IActionResult Index()
        {
            var process = Process.GetCurrentProcess();
            var info = new
            {
                // 앱, 호스트(Host) 관련
                _env.EnvironmentName,
                _env.ContentRootPath,
                _env.ApplicationName,

                // OS, Framework 관련
                RuntimeInformation.OSDescription,
                OSArchitecture = RuntimeInformation.OSArchitecture.ToString(),
                RuntimeInformation.FrameworkDescription,
                ProcessArchitecture = RuntimeInformation.ProcessArchitecture.ToString(),

                WorkingSet = process.WorkingSet64 / 1048576, // 물리 메모리 사용량(바이트)
                TotalCpuTime = process.TotalProcessorTime, // 프로세스 실행 시간

                // 시스템(환경변수) 관련
                Environment.MachineName,
                Environment.CurrentDirectory,
                Environment.SystemDirectory,
                Environment.Is64BitOperatingSystem,
                Environment.Is64BitProcess,
                Environment.ProcessorCount,

                // 시작 시각 등
                TickCount = TimeSpan.FromMicroseconds(Environment.TickCount).ToString(), // 시스템 시작 후 경과 시간(밀리초)
            };

            // CPU 정보
            ViewBag.cpu = new ManagementObjectSearcher("select * from Win32_Processor").Get();

            // 메모리 정보
            ViewBag.memory = new ManagementObjectSearcher("select * from Win32_MemoryDevice").Get();

            // 디스크 정보
            ViewBag.disk = new ManagementObjectSearcher("select * from Win32_DiskDrive").Get();

            ViewBag.Info = info;

            return View("~/Views/Setting/Server.cshtml");
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
