import Quickshell
import Quickshell.Io
import QtQuick

import qs.config
import qs.services

ShellRoot {
    IpcHandler {
        target: "keybinds-test"

        function rebind(current: string, next: string): bool {
            return Keybinds.rebind(current, next);
        }

        function resetBind(current: string): bool { return Keybinds.resetBind(current); }
        function resetAll(): void { Keybinds.resetAll(); }

        function seedResetCollision(shipped: string, current: string, occupantShipped: string): void {
            const overrides = {};
            overrides[shipped] = current;
            overrides[occupantShipped] = shipped;
            DesktopPreferences.set("keybindOverrides", overrides);
        }

        function chordFor(description: string): string {
            const found = Keybinds.binds.find(bind => bind.description === description);
            return found ? found.luaChord : "";
        }

        function overrideState(): string {
            return JSON.stringify({
                overrides: Keybinds.overrides,
                count: Object.keys(Keybinds.overrides).length,
                lastError: Keybinds.lastError
            });
        }

        function status(): string {
            const grouped = Keybinds.grouped();
            let groupedCount = 0;
            for (const group of grouped)
                groupedCount += group.binds.length;

            const superT = Keybinds.binds.find(bind => bind.description === "Terminal");

            return JSON.stringify({
                loaded: Keybinds.loaded,
                count: Keybinds.binds.length,
                groupedCount: groupedCount,
                groups: grouped.map(group => group.name),
                sample: superT ? superT.chord : "",
                emptyDescriptions: Keybinds.binds.filter(bind => !bind.description).length,
                lastError: Keybinds.lastError
            });
        }
    }
}
