import {computed, reactive, ref, toRefs, toValue} from "vue";
import {net} from "frontend/wailsjs/go/models";
import IOCountersStat = net.IOCountersStat;
import {GetNetworkCounter} from "frontend/wailsjs/go/system/InfoUtils";

const network = reactive({
    counter: {
        data: <IOCountersStat[]>[],
        interval: <any>undefined
    },
    sumCounter: {
        rate: {
            recv: -1,
            sent: -1,
            max: {
                recv: 0,
                sent: 0
            }
        },
        data: <IOCountersStat>{
            bytesRecv: -1,
            bytesSent: -1
        },
        interval: <NodeJS.Timeout|undefined>undefined,
    }
})


function loopNetworkSumCounter(){
    clearInterval(network.sumCounter.interval)
    function loop(){
        GetNetworkCounter(true).then(result=> {
            let recv = result[0].bytesRecv || 0
            let sent = result[0].bytesSent || 0

            network.sumCounter.data.bytesRecv = network.sumCounter.data.bytesRecv == -1?recv:network.sumCounter.data.bytesRecv
            network.sumCounter.data.bytesSent = network.sumCounter.data.bytesSent == -1?sent:network.sumCounter.data.bytesSent

            // 实时网速
            network.sumCounter.rate.recv = recv - network.sumCounter.data.bytesRecv
            network.sumCounter.rate.sent = sent - network.sumCounter.data.bytesSent

            network.sumCounter.rate.max.recv = Math.max(network.sumCounter.rate.max.recv, network.sumCounter.rate.recv)
            network.sumCounter.rate.max.sent = Math.max(network.sumCounter.rate.max.sent, network.sumCounter.rate.sent)

            network.sumCounter.data = result[0]
        })

        // 每秒调用一次
        network.sumCounter.interval = setTimeout(()=>{
            loop()
        },1000)
    }
    loop()
}


export function useNetworkSumCounter(){
    if(network.sumCounter.interval == null){
        loopNetworkSumCounter()
    }

    return network.sumCounter.data
}

export function useNetworkSumRate(){
    if(network.sumCounter.interval == null){
        loopNetworkSumCounter()
    }

    return network.sumCounter.rate
}

export function useNetworkSumMaxRate(){
    if(network.sumCounter.interval == null){
        loopNetworkSumCounter()
    }

    return network.sumCounter.rate.max
}
