import {reactive, computed} from "vue";
import {GetVirtualMemory} from "frontend/wailsjs/go/system/InfoUtils";
import {bytesToSizeWithUnit} from "src/utils/file/file";
import {mem} from "frontend/wailsjs/go/models";
import VirtualMemoryStat = mem.VirtualMemoryStat;

const memory = reactive({
    data: <VirtualMemoryStat>{},
    interval: <NodeJS.Timeout | undefined>undefined,
})

function loopMemory(){
    clearInterval(memory.interval)
    function loop(){
        GetVirtualMemory().then(result=> {
            memory.data = result
        })
        memory.interval = setTimeout(()=>{
            loop()
        },1000)
    }
    loop()
}

export function useMemoryUsage(){
    if(memory.interval == null){
        loopMemory()
    }

    return computed(()=> Number((memory.data.usedPercent || 0).toFixed(2)))
}


export function useMemoryUsageSizeWithByte(){
    if(memory.interval == null){
        loopMemory()
    }

    return computed(()=> memory.data.used || 0)
}

export function useMemoryUsageSize(){
    if(memory.interval == null){
        loopMemory()
    }

    return computed(()=> bytesToSizeWithUnit(memory.data.used || 0))
}

export function useMemoryTotalSize(){
    if(memory.interval == null){
        loopMemory()
    }

    return computed(()=> bytesToSizeWithUnit(memory.data.total || 0))
}

export function useMemoryTotalSizeWithByte(){
    if(memory.interval == null){
        loopMemory()
    }

    return computed(()=> memory.data.total || 0)
}
