pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import "../config" as Cfg

Item {
    id: root

    readonly property string tz: Cfg.Config.timezone || ""
    property int tzOffsetMin: 0
    property bool ready: false

    Process {
        id: tzProc
        command: ["/usr/bin/env", "TZ=" + root.tz, "date", "+%z"]
        running: root.tz !== ""
        stdout: SplitParser {
            onRead: data => {
                var s = data.trim()
                if (s.length < 5) return
                var sign = (s[0] === "-") ? -1 : 1
                var h    = parseInt(s.substring(1, 3), 10)
                var m    = parseInt(s.substring(3, 5), 10)
                root.tzOffsetMin = sign * (h * 60 + m)
                root.ready = true
            }
        }
    }

    Timer {
        interval: 1800000
        running: root.tz !== ""
        repeat: true
        onTriggered: tzProc.running = true
    }

    function toTz(date) {
        if (!root.tz) return date
        return new Date(date.getTime()
            + date.getTimezoneOffset() * 60000
            + root.tzOffsetMin * 60000)
    }

    function tzOffsetHours() {
        if (!root.tz) return -(new Date().getTimezoneOffset()) / 60
        return root.tzOffsetMin / 60
    }
}
