package io.wdd.agent.executor.status;

import io.wdd.common.utils.FormatUtils;
import lombok.extern.slf4j.Slf4j;
import oshi.hardware.NetworkIF;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;


@Slf4j
public class NetworkInterfaceSpeedCallable implements Callable<String[]> {

    private NetworkIF networkInterface;

    public NetworkInterfaceSpeedCallable(NetworkIF networkInterface) {
        this.networkInterface = networkInterface;
    }

    @Override
    public String[] call() throws Exception {
        String[] result = {
                "sendSpeed",
                "recvSpeed"
        };

        long recvPre = networkInterface.getBytesRecv();
        long sentPre = networkInterface.getBytesSent();
        long pre = new Date().getTime();

        TimeUnit.SECONDS.sleep(1);

        long recv = networkInterface.getBytesRecv();
        long sent = networkInterface.getBytesSent();
        long now = new Date().getTime();

        long recvSpeed = (recv - recvPre) / (now - pre);
        long sentSpeed = (sent - sentPre) / (now - pre);

        result[0] = FormatUtils.formatData(sentSpeed) + "/s";
        result[1] = FormatUtils.formatData(recvSpeed) + "/s";

        return result;
    }
}
