pragma Singleton
import Quickshell
import Quickshell.Io
import QtQuick

Singleton {
    id: root

    property int usedMb:  0
    property int totalMb: 0
    property int usage:   0

    Timer {
        interval: 2000
        running: true
        repeat: true
        triggeredOnStart: true
        onTriggered: {
            _proc.running = false
            _proc.running = true
        }
    }

    Process {
        id: _proc
        command: ["bash", "-c", "grep -E '^(MemTotal|MemAvailable):' /proc/meminfo | awk '{print $2}'"]
        stdout: SplitParser {
            property int _total: 0
            property int _avail: 0
            property int _lines: 0

            onRead: line => {
                const v = parseInt(line.trim())
                if (isNaN(v)) return
                if (_lines === 0) _total = v
                else              _avail = v
                _lines++
                if (_lines === 2) {
                    root.totalMb = Math.round(_total / 1024)
                    root.usedMb  = Math.round((_total - _avail) / 1024)
                    root.usage   = Math.round((1 - _avail / _total) * 100)
                    _lines = 0
                }
            }
        }
    }
}
