pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io

Item {
    property real percentage: 0
    property bool charging: false
    property real energy: 0
    property real voltage: 0
    property int charge_cycle: 0
    property real time_to_empty: 0
    property real energy_rate: 0

    function parseUpower(line) {
        line = line.trim()

        if (line.startsWith("percentage:")) {
            percentage = parseInt(line.split(":")[1])
            // console.log("percentage =", percentage)
        }

        else if (line.startsWith("state:")) {
            charging = !line.includes("discharging")
            // console.log("charging =", charging)
        }

        else if (line.startsWith("energy:")) {
            energy = parseFloat(line.split(":")[1])
            // console.log("energy =", energy)
        }

        else if (line.startsWith("voltage:")) {
            voltage = parseFloat(line.split(":")[1])
            // console.log("voltage =", voltage)
        }

        else if (line.startsWith("energy-rate:")) {
            energy_rate = parseFloat(line.split(":")[1])
            // console.log("energy_rate =", energy_rate)
        }

        else if (line.startsWith("charge-cycles:")) {
            charge_cycle = parseInt(line.split(":")[1])
            // console.log("charge_cycle =", charge_cycle)
        }

        else if (line.startsWith("time to empty:")) {
            time_to_empty = parseFloat(line.split(":")[1])
            // console.log("time_to_empty =", time_to_empty)
        }
    }

    Process {
        id: upowerProc
        command: ["bash", "-c", "upower -i $(upower -e | grep BAT)"]

        stdout: SplitParser {
            onRead: function(data) {
                parseUpower(data)
                // console.log("battery available:", data)
            }
        }
    }

    Timer {
        id: pollTimer
        interval: 1000
        running: false
        repeat: true
        triggeredOnStart: true
        onTriggered: upowerProc.running = true
    }

    function start() {
        pollTimer.start()
        upowerProc.running = true
    }

    function stop() {
        pollTimer.stop()
    }
}