(:~
 : WebSocket LSP 
 : @author Andy Bunce
 :)
module namespace lsp-ws = 'lsp-ws';

import module namespace lsprpc = 'lsprpc' at 'jsonrpc.xqm';


declare 
%ws:error('/lsp', '{$error}') 
function lsp-ws:error($error) { 
  trace($error,"ERR ")
};

(:~ 
 : Creates a WebSocket connection. Registers the user and notifies all clients.
 :)
declare
  %ws:connect('/lsp')
function lsp-ws:connect() as empty-sequence() {
let $id:=ws:id()=>trace("CONNECT: ")
return  (
  ws:set($id, "id", $id),
  ws:set($id, "initialized", false()) 
)
};

(:~ 
 : Processes a WebSocket message.
 : @param  $message  message
 :)
declare
  %ws:message('/lsp', '{$message}')
function lsp-ws:message(
  $message  as xs:string
) as empty-sequence() {
 
  let $json := lsprpc:parse($message=>trace("MSG "))
  return if(exists($json))
         then lsprpc:reply($json)
         else message($message,"bad RPC: ")
};


(:~ 
 : Closes a WebSocket connection.
 :)
declare
  %ws:close('/lsp')
function lsp-ws:close() as empty-sequence() {
  message("SOCKET CLOSE: " || ws:id())
};
