pragma Singleton
import Quickshell
import Quickshell.Io
import QtQuick

Singleton {
    id: root

    property int usage: 0
    property int temp:  0

    property var _prevTotal: null
    property var _prevIdle:  null

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

    Process {
        id: _statProc
        command: ["bash", "-c", "grep '^cpu ' /proc/stat"]
        stdout: SplitParser {
            onRead: line => {
                const p     = line.trim().split(/\s+/)
                const idle  = parseInt(p[4]) + parseInt(p[5])
                const total = p.slice(1, 8).reduce((a, v) => a + parseInt(v), 0)
                if (root._prevTotal !== null) {
                    const dt = total - root._prevTotal
                    const di = idle  - root._prevIdle
                    root.usage = dt > 0 ? Math.round((1 - di / dt) * 100) : 0
                }
                root._prevTotal = total
                root._prevIdle  = idle
            }
        }
    }

    Process {
        id: _tempProc
        command: ["bash", "-c", "for d in /sys/class/hwmon/hwmon*/; do name=$(cat ${d}name 2>/dev/null); if [ \"$name\" = 'coretemp' ]; then awk '{print int($1/1000)}' \"${d}temp1_input\" 2>/dev/null && break; elif [ \"$name\" = 'k10temp' ]; then awk '{print int($1/1000)}' \"${d}temp1_input\" 2>/dev/null && break; fi; done"]
        stdout: SplitParser {
            onRead: line => {
                const v = parseInt(line.trim())
                if (!isNaN(v) && v > 0) root.temp = v
            }
        }
    }
}
