package cn.reghao.tnb.oss.store.service;

import cn.reghao.tnb.oss.api.dto.disk.DiskPartition;
import cn.reghao.tnb.oss.api.dto.disk.DiskStore;
import cn.reghao.tnb.oss.api.dto.disk.DiskVolume;
import org.springframework.stereotype.Service;
import oshi.SystemInfo;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2024-10-21 09:57:18
 */
@Service
public class DiskService {
    private final HardwareAbstractionLayer hal;
    private final FileSystem fs;

    public DiskService() {
        SystemInfo si = new oshi.SystemInfo();
        this.hal = si.getHardware();
        this.fs = si.getOperatingSystem().getFileSystem();
    }

    public List<DiskVolume> getFileStore() {
        List<DiskVolume> list = fs.getFileStores().stream()
                .filter(osFileStore -> !osFileStore.getUUID().isBlank())
                .map(osFileStore -> {
                    String name = osFileStore.getName();
                    String volume = osFileStore.getVolume();
                    String mountPoint = osFileStore.getMount();
                    String blockId = osFileStore.getUUID();
                    String fsType = osFileStore.getType();
                    long totalSpace = osFileStore.getTotalSpace();
                    long usableSpace = osFileStore.getUsableSpace();
                    long freeSpace = osFileStore.getFreeSpace();
                    long totalInodes = osFileStore.getTotalInodes();
                    long freeInodes = osFileStore.getFreeInodes();
                    return new DiskVolume(name, volume, mountPoint, fsType, blockId,
                            totalSpace, usableSpace, totalInodes, freeInodes);
                }).collect(Collectors.toList());
        return list;
    }

    public List<DiskStore> getDiskStore() {
        List<DiskStore> diskStores = hal.getDiskStores().stream().map(hwDiskStore -> {
            String model = hwDiskStore.getModel();
            String name = hwDiskStore.getName();
            long size = hwDiskStore.getSize();
            List<DiskPartition> partitions = hwDiskStore.getPartitions().stream().map(hwPartition -> {
                String partitionName = hwPartition.getIdentification();
                String mountPoint = hwPartition.getMountPoint();
                String blockId = hwPartition.getUuid();
                String fsType = hwPartition.getType();
                long partitionSize = hwPartition.getSize();
                return new DiskPartition(partitionName, mountPoint, blockId, fsType, partitionSize);
            }).collect(Collectors.toList());
            return new DiskStore(model, name, size, partitions);
        }).collect(Collectors.toList());
        return diskStores;
    }
}
