import {EditorSelection} from "@codemirror/state";
import {keymap} from "@codemirror/view";

function spawnNewCursor(view, forward) {
    const { state } = view
    const selection = state.selection
    const newRanges = []

    for (let range of selection.ranges) {
        // Keep existing cursor
        newRanges.push(range)
        newRanges.push(view.moveVertically(range, forward, 1));
    }

    view.dispatch({
        selection: EditorSelection.create(newRanges)
    })
    return true
}

export const multiCursorKeymap = keymap.of([
    {
        key: "Ctrl-Alt-ArrowDown", // Control+Option+Down on Mac
        run: (view) => spawnNewCursor(view, true),
    },
    {
        key: "Ctrl-Alt-ArrowUp", // Control+Option+Down on Mac
        run: (view) => spawnNewCursor(view, false),
    }
])

export const commandPalette = keymap.of([{
    key: "Cmd-p",
    run: () => {
        let event = new CustomEvent('dq-showcommands');
        window.dispatchEvent(event);

        return true;
    }
}, {
    key: "Cmd-P",
    run: () => {
        let event = new CustomEvent('dq-rerunlastcommand');
        window.dispatchEvent(event);

        return true;
    }
}, {
    key: "Cmd-k",
    run: (view) => {
        const {state} = view;
        const changes = [];

        for (let range of state.selection.ranges) {
            const line = state.doc.lineAt(range.head);
            changes.push({
                from: line.from,
                to: line.to < state.doc.length ? line.to + 1 : line.to,
                insert: ""
            });
        }

        view.dispatch({
            changes: changes,
            sequential: true
        });

        return true;
    }
}]);
