import QtQuick
import Quickshell
import Quickshell.Io
import qs.Common
import qs.Services
import qs.Widgets
import qs.Modules.Plugins

PluginComponent {
    id: root

    property bool vaultUnlocked: false

    function refreshLockState() {
        if (!statusProcess.running)
            statusProcess.exec(["rbw", "unlocked"]);
    }

    function toggleLock() {
        if (root.vaultUnlocked) {
            Quickshell.execDetached(["rbw", "lock"]);
        } else {
            Quickshell.execDetached(["rbw", "unlock"]);
        }
    }

    pillClickAction: () => root.toggleLock()

    Component.onCompleted: refreshLockState()

    Timer {
        interval: 2500
        repeat: true
        running: true
        onTriggered: root.refreshLockState()
    }

    Process {
        id: statusProcess
        command: ["rbw", "unlocked"]
        onExited: (exitCode, _exitStatus) => {
            root.vaultUnlocked = exitCode === 0;
        }
    }

    horizontalBarPill: Component {
        MouseArea {
            implicitWidth: iconH.implicitWidth
            implicitHeight: iconH.implicitHeight
            hoverEnabled: true
            cursorShape: Qt.PointingHandCursor
            onClicked: root.toggleLock()

            DankIcon {
                id: iconH
                name: root.vaultUnlocked ? "lock_open_right" : "lock"
                size: root.iconSize
                color: parent.containsMouse ? Theme.primary : Theme.surfaceText
            }
        }
    }

    verticalBarPill: Component {
        MouseArea {
            implicitWidth: iconV.implicitWidth
            implicitHeight: iconV.implicitHeight
            hoverEnabled: true
            cursorShape: Qt.PointingHandCursor
            onClicked: root.toggleLock()

            DankIcon {
                id: iconV
                name: root.vaultUnlocked ? "lock_open_right" : "lock"
                size: root.iconSize
                color: parent.containsMouse ? Theme.primary : Theme.surfaceText
                anchors.horizontalCenter: parent.horizontalCenter
            }
        }
    }
}
