(:~ web socket for ace
:)
module namespace lsp="urn:quodatum:vscode";
import module namespace ws = "http://basex.org/modules/ws";

declare 
%ws:connect('/ws/exampleServer') 
function lsp:connect() 
as empty-sequence(){
  let $_:=trace(ws:id(),"BaseX socket id: ")
  return ()
 };
 
 (:~ 
 : Processes a WebSocket message.
 : @param  $message  message
 :)
declare
  %ws:message('/ws/exampleServer', '{$message}')
function lsp:message(
  $message  as xs:string
) as empty-sequence() {
  let $json:=json:parse($message, map{ 'format': 'xquery' })
  let $id:=$json?id
  let $_:=trace($id,"MESSAGE id: ")
  return  switch($json?method=>trace("method: "))
          case "initialize" return
                let $a:=map{
                  "capabilities":map{"textDocumentSync":2,
                                    "completionProvider":map{"resolveProvider":false(),"triggerCharacters":["\",":"]},
                                    "hoverProvider":true(),
                                    "documentSymbolProvider":true(),
                                    "documentRangeFormattingProvider":false(),
                                    "colorProvider":map{},
                                    "foldingRangeProvider":true(),
                                    "selectionRangeProvider":true(),
                                    "documentLinkProvider":map{}
                                    }
                                    }
                let $a:=trace($a,"A: ")
                return lsp:send-result($a,$id,ws:id())
          default 
                return error()
};

declare %ws:error('/ws/exampleServer', '{$error}') 
function lsp:error($error) 
{ 
 let $_:=trace($error,"ERROR ")
  return ()
};

(:~ 
 : Closes a WebSocket connection. Unregisters the user and notifies all clients.
 :)
declare
  %ws:close('/ws/exampleServer')
function lsp:close() as empty-sequence() {
   let $_:=trace("CLOSE")
  return ()
};



declare
function lsp:send-result($result as map(*),$rpcId as xs:string, $wsId as xs:string) 
as empty-sequence()
{
  let $json:=map{"jsonrpc":"2.0","id":$rpcId,"result":$result}=>trace("RESULT: ")            
  return ws:send($json,$wsId)           
};

