import QtQuick
import Quickshell
import Quickshell.Io

Item {
    id: root

    property string configPath:
        Quickshell.env("HOME") + "/.config/quickshell/config/config.qml"

    Process {
        id: writerProc
        running: false
        onExited: (code) => {
            if (code !== 0)
                console.warn("[ConfigWriter] Patch failed (exit " + code + ")")
        }
        property string _name: "ConfigWriter"
    }

    function writeInt(key, value) {
        const n = Math.round(value).toString()
        const sh = "sed -i" +
            " -e 's/\\(property int[[:space:]]\\+\\b" + key + "\\b:[ ]*\\)[0-9.]\\+/\\1" + n + "/'" +
            " " + JSON.stringify(root.configPath)
        writerProc.command = ["/bin/sh", "-c", sh]
        writerProc.running = true
    }

    function writeBool(key, value) {
        const v = value ? "true" : "false"
        const sh = "sed -i" +
            " -e 's/\\(property bool[[:space:]]\\+\\b" + key + "\\b:[ ]*\\)\\(true\\|false\\)/\\1" + v + "/'" +
            " " + JSON.stringify(root.configPath)
        writerProc.command = ["/bin/sh", "-c", sh]
        writerProc.running = true
    }

    function writeInts(pairs) {
        let args = ""
        for (let i = 0; i < pairs.length; i++) {
            const n = Math.round(pairs[i].value).toString()
            args += " -e 's/\\(property int[[:space:]]\\+\\b" + pairs[i].key + "\\b:[ ]*\\)[0-9.]\\+/\\1" + n + "/'"
        }
        const sh = "sed -i" + args + " " + JSON.stringify(root.configPath)
        writerProc.command = ["/bin/sh", "-c", sh]
        writerProc.running = true
    }

    function writeArray(key, pairsQml) {
        const sh =
            "CFG=" + JSON.stringify(root.configPath) + "\n" +
            "QS_PAIRS='" + pairsQml + "'\n" +
            "awk -v pairs=\"$QS_PAIRS\" '" +
                "/^[[:space:]]*property var[[:space:]]+" + key + ":[[:space:]]/{print \"    property var " + key + ": \"pairs;sk=/\\]/?0:1;next}" +
                "sk&&/\\]/{sk=0;next}" +
                "sk{next}" +
                "{print}'" +
            " \"$CFG\" > \"${CFG}.tmp\" && mv \"${CFG}.tmp\" \"$CFG\"\n"
        writerProc.command = ["/bin/sh", "-c", sh]
        writerProc.running = true
    }

    function writeScript(sh) {
        writerProc.command = ["/bin/sh", "-c", sh]
        writerProc.running = true
    }
}
