////
// The terminal communicates with the shell via websockets.

import type { Message } from "../shared/types.js"
import { sessionID } from "./session.js"
import { handleMessage } from "./shell.js"
import { addErrorMessage } from "./scrollback.js"

const MAX_RETRIES = 5
let retries = 0

let ws: WebSocket | null = null

// open our websocket connection
export function startConnection() {
    const url = new URL('/ws', location.href)
    url.protocol = url.protocol.replace('http', 'ws')
    ws = new WebSocket(url)

    ws.onmessage = receive
    ws.onclose = retryConnection
    ws.onerror = () => ws?.close()
}

// send any message
export function send(msg: Message) {
    if (!msg.session) msg.session = sessionID
    ws?.readyState === 1 && ws.send(JSON.stringify(msg))
    console.log("-> send", msg)
}

async function receive(e: MessageEvent) {
    const data = JSON.parse(e.data) as Message
    console.log("<- receive", data)
    await handleMessage(data)
}

// close it... plz don't do this, though
export function close() {
    ws?.close(1000, 'bye')
}

function retryConnection() {
    if (retries >= MAX_RETRIES) {
        addErrorMessage(`!! Failed to reconnect ${retries} times. Server is down.`)
        if (ws) ws.onclose = () => { }
        return
    }
    retries++
    addErrorMessage(`!! Connection lost. Retrying...`)
    setTimeout(startConnection, 2000)
}
