package cn.monitor.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.util.core.IsKit;

public class SystemInfoService
{
	/**
	 * 获取服务器启动时间
	 */
	public static Date getServerStartDate() {
		long time = ManagementFactory.getRuntimeMXBean().getStartTime();
		return new Date(time);
	}
	/**
	 * String userName = map.get("USERNAME");// 获取用户名
	 * String computerName = map.get("COMPUTERNAME");// 获取计算机名
	 *  String userDomain = map.get("USERDOMAIN");// 获取计算机域名
	 */
	public static Map<String, String> getSystemName()
	{
		Map<String, String> map = System.getenv();
		return map;
	}

	/**
	 * 获取当前操作系统名称.
	 * return 操作系统名称 例如:windows xp,linux 等.
	 */
	public static String getOSName() {
		return System.getProperty("os.name").toLowerCase();
	}

	public static String getHostName()
	{
		InetAddress ia = null;
		try {
			ia = InetAddress.getLocalHost();
		} catch (Exception e) {}
		if(IsKit.isNotNullOrEmpty(ia)) {
			return ia.getHostName();//192.168.1.3
		}
		return null;
	}

	public static String getLocalIp()
	{
		InetAddress ia = null;
		try {
			//DESKTOP-FHJG13I/192.168.1.3
			ia = InetAddress.getLocalHost();
		} catch (Exception e) {}
		if(IsKit.isNotNullOrEmpty(ia)) {
			return ia.getHostAddress();//192.168.1.3
		}
		return null;
	}


	public static String getLocalMac()
	{
		StringBuffer sb = new StringBuffer("");
		//获取网卡，获取地址
		try {
			InetAddress ia = InetAddress.getLocalHost();
			byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
			for(int i=0; i<mac.length; i++) {
				if(i!=0) {
					sb.append("-");
				}
				//字节转换为整数
				int temp = mac[i]&0xff;
				String str = Integer.toHexString(temp);
				if(str.length()==1) {
					sb.append("0"+str);
				}else {
					sb.append(str);
				}
			}
		} catch (Exception e) {}

		return sb.toString().toUpperCase();
	}


	/**
	 * 获取unix网卡的mac地址.
	 * 非windows的系统默认调用本方法获取.如果有特殊系统请继续扩充新的取mac地址方法.
	 *
	 * @return mac地址
	 */
	public static String getUnixMACAddress()
	{
		String mac = null;
		BufferedReader bufferedReader = null;
		Process process;
		try {
			// linux下的命令，一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
			process = Runtime.getRuntime().exec("ifconfig eth0");
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line;
			int index;
			while ((line = bufferedReader.readLine()) != null) {
				index = line.toLowerCase().indexOf("hwaddr");// 寻找标示字符串[hwaddr]
				if (index >= 0) {// 找到了
					mac = line.substring(index + "hwaddr".length() + 1).trim();//  取出mac地址并去除2边空格
					break;
				}
			}
		} catch (Exception e) {

		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (Exception e1) {}
		}
		return mac;
	}
	/**
	 * 获取widnows网卡的mac地址.
	 * @return mac地址
	 */
	public static List<String> getWindowsMACAddress()
	{
		List<String> macList = new ArrayList<String>();
		String mac = null;
		BufferedReader bufferedReader = null;
		Process process;
		try {
			//windows下的命令，显示信息中包含有mac地址信息
			process = Runtime.getRuntime().exec("ipconfig /all");
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
			String line;
			int index;
			while ((line = bufferedReader.readLine()) != null) {
				index = line.toLowerCase().indexOf("physical address");// 寻找标示字符串[physical address]
				if (index == -1) {
					index = line.indexOf("物理地址");
				}
				if (index >= 0) {// 找到了
					index = line.indexOf(":");// 寻找":"的位置
					if (index >= 0) {
						mac = line.substring(index + 1).trim();//  取出mac地址并去除2边空格
					}
					macList.add(mac);
				}
			}

		} catch (Exception e) {
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (Exception e1) {}
		}
		return macList;
	}
	
	/**
	    * @param drive 硬盘驱动器分区 如C,D
	    * @return 该分区的卷标
	    */
	   public static String getHDSerial(String drive) {
	       String result = "";
	       try {
	           File file = File.createTempFile("tmp", ".vbs");
	           file.deleteOnExit();
	           FileWriter fw = new java.io.FileWriter(file);

	           String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
	                   + "Set colDrives = objFSO.Drives\n" + "Set objDrive = colDrives.item(\"" + drive + "\")\n"
	                   + "Wscript.Echo objDrive.SerialNumber";
	           fw.write(vbs);
	           fw.close();
	           Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
	           BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
	           String line;
	           while ((line = input.readLine()) != null) {
	               result += line;
	           }
	           input.close();
	           file.delete();
	       } catch (Exception e) {

	       }
	       if (result.trim().length() < 1 || result == null) {
	           result = "无磁盘ID被读取";
	       }
	       return result.trim();
	   }
		/**
	     * 获取CPU号,多CPU时,只取第一个
	     * @return
	     */
	    public static String getCPUSerial() 
	    {
	        String result = "";
	        try {
	            File file = File.createTempFile("tmp", ".vbs");
	            file.deleteOnExit();
	            FileWriter fw = new java.io.FileWriter(file);

	            String vbs = "On Error Resume Next \r\n\r\n" + "strComputer = \".\"  \r\n"
	                    + "Set objWMIService = GetObject(\"winmgmts:\" _ \r\n"
	                    + "    & \"{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\cimv2\") \r\n"
	                    + "Set colItems = objWMIService.ExecQuery(\"Select * from Win32_Processor\")  \r\n "
	                    + "For Each objItem in colItems\r\n " + " Wscript.Echo objItem.ProcessorId  \r\n "
	                    + "    exit for  ' do the first cpu only! \r\n" + "Next                    ";

	            fw.write(vbs);
	            fw.close();
	            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
	            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
	            String line;
	            while ((line = input.readLine()) != null) {
	                result += line;
	            }
	            input.close();
	            file.delete();
	        } catch (Exception e) {
	        }
	        if (result.trim().length() < 1 || result == null) {
	            result = "无CPU_ID被读取";
	        }
	        return result.trim();
	    }
}

