package cn.reghao.devops.common.machine;

import cn.reghao.jutil.jdk.machine.data.MachineData;
import cn.reghao.jutil.jdk.machine.data.detail.MemoryDetail;
import oshi.hardware.GlobalMemory;
import oshi.hardware.VirtualMemory;

/**
 * @author reghao
 * @date 2019-10-25 13:21:25
 */
public class Memory implements MachineData<MemoryDetail, MemoryStat> {
    private final GlobalMemory globalMemory;
    private final VirtualMemory virtualMemory;
    private MemoryDetail memoryDetail;

    public Memory(GlobalMemory globalMemory) {
        this.globalMemory = globalMemory;
        this.virtualMemory = globalMemory.getVirtualMemory();
    }

    @Override
    public MemoryDetail detail() {
        long total = globalMemory.getTotal();
        long avail = globalMemory.getAvailable();
        long swapTotal = virtualMemory.getSwapTotal();
        long swapUsed = virtualMemory.getSwapUsed();

        if (memoryDetail == null) {
            memoryDetail = new MemoryDetail(total, avail, total-avail, swapTotal, swapTotal-swapUsed);
        }

        return memoryDetail;
    }

    @Override
    public MemoryStat stat() {
        if (memoryDetail == null) {
            memoryDetail = detail();
        }

        long total = globalMemory.getTotal();
        long avail = globalMemory.getAvailable();
        memoryDetail.setAvail(avail);
        memoryDetail.setUsed(total-avail);

        long swapTotal = virtualMemory.getSwapTotal();
        long swapUsed = virtualMemory.getSwapUsed();
        memoryDetail.setAvail(swapTotal-swapUsed);
        return null;
    }
}
