(:~
 app
 :)
module namespace app = 'app/common';
import module namespace cm = "app/cm" at "common.xqm";
import module namespace wsa = 'app/sockets' at "api-sockets.xqm";

(:~
 : Redirects to the start page.
 : @return redirection
 :)
declare %rest:path('/app')
function app:redirect(
) as element(rest:response) {
  web:redirect('/app/home')
};

(:~
 : Returns a file.
 : @param  $file  file or unknown path
 : @return rest binary data
 :)
declare %rest:path('/app/static/{$file=.+}')
  %output:method('basex')
  %perm:allow('public')
function app:file( $file  as xs:string) 
as item()+ {
  let $path:=file:base-dir() || 'static/' || $file
  return if(file:exists($path))
        then cm:response-file($path)
        else (
          <rest:response>
          <http:response status="404">
            <http:header name="Content-Language" value="en"/>
            <http:header name="Content-Type" value="text/plain; charset=utf-8"/>
          </http:response>
        </rest:response>,
        "The requested resource is not available."
        )
};



(:~ start page. :)
declare %rest:path('/app/home')
function app:home() as item()* {
 rest:init(true()),
 cm:htmx2("home.htm", map{"version" :"0.0.2"})
};



declare %rest:path('/app/socket')
function app:sockets() {
  cm:htmx2("sockets.htm", map{"sockets": wsa:wsids()=>reverse()
                             ,"count":count( wsa:wsids())
                             })
}; 

declare %rest:path('/app/socket/{$wsid}')
function app:socket($wsid) {
  let $files:=ws:get($wsid,"files")
  let $file:= $files($files=>map:keys()=>head())
  let $doc:=ws:get($wsid,$file?textDocument) 
  return cm:htmx2("socket.htm", map{
    "wsid": $wsid,
    "connectTime": ws:get($wsid,"connectTime"),
    "files": map:keys($files),
    "file1": json:serialize($file, { 'format': 'w3', 'indent': 'no' }),
    "doc": $doc                         
    })
}; 

declare %rest:path('/app/dev')
function app:dev() {
  cm:htmx2("dev/home.htm", map{})
}; 

(:~ log as strings :)
declare function app:logs() {
(admin:logs()=>foot()=>admin:logs())
[@type eq 'LSP']
[starts-with(.,"⬅️")]
/substring(.,2)
};