package com.philisense.www.common.config;

import java.lang.management.ManagementFactory;
import java.net.UnknownHostException;
import java.util.*;

import com.philisense.www.utils.Arith;
import com.philisense.www.utils.ip.IpUtils;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

/**
 * 服务器相关信息
 * 
 * @author mister
 */
public class Server
{
    
    private static final int OSHI_WAIT_SECOND = 1000;
    
    /**
     * CPU相关信息
     */
    private Map<String,Object> cpu = new HashMap<String,Object>();

    /**
     * 內存相关信息
     */
    private Map<String,Object> mem = new HashMap<String,Object>();

    /**
     * JVM相关信息
     */
    private Map<String,Object> jvm = new HashMap<String,Object>();

    /**
     * 服务器相关信息
     */
    private Map<String,Object> sys = new HashMap<String,Object>();

    /**
     * 磁盘相关信息
     */
    private List<Map<String,Object>> sysFiles = new LinkedList<Map<String,Object>>();

    public Map<String,Object> getCpu()
    {
        return cpu;
    }

    public void setCpu(Map<String,Object> cpu)
    {
        this.cpu = cpu;
    }

    public Map<String,Object> getMem()
    {
        return mem;
    }

    public void setMem(Map<String,Object> mem)
    {
        this.mem = mem;
    }

    public Map<String,Object> getJvm()
    {
        return jvm;
    }

    public void setJvm(Map<String,Object> jvm)
    {
        this.jvm = jvm;
    }

    public Map<String,Object> getSys()
    {
        return sys;
    }

    public void setSys(Map<String,Object> sys)
    {
        this.sys = sys;
    }

    public List<Map<String,Object>> getSysFiles()
    {
        return sysFiles;
    }

    public void setSysFiles(List<Map<String,Object>> sysFiles)
    {
        this.sysFiles = sysFiles;
    }

    public void copyTo() throws Exception
    {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();

        setCpuInfo(hal.getProcessor());

        setMemInfo(hal.getMemory());

        setSysInfo();

        setJvmInfo();

        setSysFiles(si.getOperatingSystem());
    }

    /**
     * 设置CPU信息
     */
    private void setCpuInfo(CentralProcessor processor)
    {
        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(OSHI_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;

        
        cpu.put("CpuNum", processor.getLogicalProcessorCount());
        cpu.put("Total", totalCpu);
        cpu.put("Sys", cSys);
        cpu.put("Used", user);
        cpu.put("Wait", iowait);
        cpu.put("Free", idle);
    }

    /**
     * 设置内存信息
     */
    private void setMemInfo(GlobalMemory memory)
    {

        
        mem.put("Total", memory.getTotal());
        mem.put("Used", memory.getTotal() - memory.getAvailable());
        mem.put("Free", memory.getAvailable());
    }

    /**
     * 设置服务器信息
     */
    private void setSysInfo()
    {
        Properties props = System.getProperties();
        
        sys.put("ComputerName", IpUtils.getHostName());
        sys.put("ComputerIp", IpUtils.getHostIp());
        sys.put("OsName", props.getProperty("os.name"));
        sys.put("setOsArch", props.getProperty("os.arch"));
        sys.put("UserDir", props.getProperty("user.dir"));
    }

    /**
     * 设置Java虚拟机
     */
    private void setJvmInfo() throws UnknownHostException
    {
        Properties props = System.getProperties();
        
        jvm.put("Total", Runtime.getRuntime().totalMemory());
        jvm.put("Max", Runtime.getRuntime().maxMemory());
        jvm.put("Free", Runtime.getRuntime().freeMemory());
        jvm.put("Version", props.getProperty("java.version"));
        jvm.put("Home", props.getProperty("java.home"));
        jvm.put("Name", ManagementFactory.getRuntimeMXBean().getVmName());
        jvm.put("StartTime", getServerStartDate());
        jvm.put("RunTime", getDatePoor(new Date(), getServerStartDate()));
    }

    /**
     * 设置磁盘信息
     */
    private void setSysFiles(OperatingSystem os)
    {
        FileSystem fileSystem = os.getFileSystem();
        List<OSFileStore> fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray)
        {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;
            Map<String,Object> sysFile = new HashMap<String,Object>();
                       
            sysFile.put("DirName", fs.getMount());
            sysFile.put("SysTypeName", fs.getType());
            sysFile.put("TypeName", fs.getName());
            sysFile.put("Total", convertFileSize(total));
            sysFile.put("Free", convertFileSize(free));
            sysFile.put("Used", convertFileSize(used));
            sysFile.put("Usage", Arith.mul(Arith.div(used, total, 4), 100));
            
            sysFiles.add(sysFile);
        }
    }

    /**
     * 字节转换
     * 
     * @param size 字节大小
     * @return 转换后值
     */
    public String convertFileSize(long size)
    {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb)
        {
            return String.format("%.1f GB", (float) size / gb);
        }
        else if (size >= mb)
        {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        }
        else if (size >= kb)
        {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        }
        else
        {
            return String.format("%d B", size);
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }
}
