import {basicSetup, EditorView} from "codemirror"
import { EditorState } from '@codemirror/state';
import { LSPClient, LSPPlugin, languageServerSupport } from "@codemirror/lsp-client";
import {StreamLanguage} from "@codemirror/language"
import { xQuery } from "@codemirror/legacy-modes/mode/xquery"

function simpleWebSocketTransport(uri) {
    let handlers = [];
    return new Promise(function (resolve, reject) {
        let sock = new WebSocket(uri);
  
        sock.onmessage = e => { for (let h of handlers) h(e.data.toString()); };
        sock.onerror = e => reject(e);
        sock.onopen = () => resolve({
            socket: sock,
            send: (message) => sock.send(message),
            subscribe: (handler) => handlers.push(handler),
            unsubscribe: (handler) => handlers = handlers.filter(h => h != handler)
        });
    }
    );
};
simpleWebSocketTransport("ws://localhost:3000/ws/lsp")
        .then(transport => {
           
            client = new LSPClient().connect(transport);

            let extLsp = languageServerSupport(client, file, "xquery");
            
            const doc = view.state.doc.toString();
            const state = lsp.createEditorState(doc, [...lsp.baseExts, extLsp, extLint]);
            view.setState(state);
        })
        .catch(r => {  alert("connection failed: " + server) });


new EditorView({
  doc: "xquery version '3.1';\n(:~ comment:)\nmodule namespace pdfbox='ns';\n",
  extensions: [basicSetup, StreamLanguage.define(xQuery)],
  parent: document.body
});