using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace nft.win32util
{
	/// <summary>
	/// Get global memory informations.
	/// each values are obtained when the object created. 
	/// </summary>
	public class GlobalMemoryInfo
	{
        [return: MarshalAs(UnmanagedType.Bool)]
		[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        extern static bool GlobalMemoryStatusEx([In,Out] MemoryStatusEx lpBuffer);
        
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public class MemoryStatusEx {
            public uint dwLength;
            public uint dwMemoryLoad;
            public ulong ullTotalPhys; // physical memory total
            public ulong ullAvailPhys; // physical memory available
            public ulong ullTotalPageFile; // page files total
            public ulong ullAvailPageFile; // page files available
            public ulong ullTotalVirtual; // virtual memory total
            public ulong ullAvailVirtual; // virtual memory available
            public ulong ullAvailExtendedVirtual;
            public MemoryStatusEx() {
                this.dwLength = (uint)Marshal.SizeOf(typeof(MemoryStatusEx));
            }
        }

		private readonly MemoryStatusEx msinfo;

		public GlobalMemoryInfo()
		{
            msinfo = new MemoryStatusEx();
            if (!GlobalMemoryStatusEx(msinfo)) {
                Debug.WriteLine(Marshal.GetLastWin32Error());
            }
		}

		public ulong PhysicalMemTotal	{ get { return msinfo.ullTotalPhys; } }
        public ulong PhysicalMemAvailable { get { return msinfo.ullAvailPhys; } }
        public ulong PageFileTotal { get { return msinfo.ullTotalPageFile; } }
        public ulong PageFileAvailable { get { return msinfo.ullAvailPageFile; } }
        public ulong VirtualMemTotal { get { return msinfo.ullTotalVirtual; } }
        public ulong VirtualMemAvailable { get { return msinfo.ullAvailVirtual; } }
	}
}
