import {reactive} from "vue";
import {net} from "frontend/wailsjs/go/models";
import IOCountersStat = net.IOCountersStat;
import {GetNetworkCounter} from "frontend/wailsjs/go/system/InfoUtils";
import moment from "moment";

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
        },
        lastTime: moment(0),
        interval: <NodeJS.Timeout|undefined>undefined,
    }
})


function loopNetworkSumCounter(){
    clearInterval(network.sumCounter.interval)
    let delay = 1000
    function loop(){
        let fixed = 0
        GetNetworkCounter(true).then(result=> {
            let now = moment()
            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

            // 避免因 webView 进入休眠/计时器误差 导致数据异常
            if(now.diff(network.sumCounter.lastTime,'s') <= 1){
                // 实时网速
                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]

            // 修正计时器延迟
            fixed = Math.max(delay - now.diff(network.sumCounter.lastTime,'ms'), 0)
            network.sumCounter.lastTime = now
        })

        // 每秒调用一次
        network.sumCounter.interval = setTimeout(()=>{
            loop()
        },delay - fixed)
    }
    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
}
