import { containerExists, getContainerShell } from './containers.js'

export async function upgrade(sessions, request, path) {
  const [container, sessionId] = path.splice(2)
  const session = sessions[sessionId]

  if (session && session.container !== container) {
    console.log('wrong session')
    return false
  }

  if (!(await containerExists(container))) {
    console.log('no container')
    return false
  }

  if (!session) {
    sessions[sessionId] = { container }
  }

  request.session = sessions[sessionId]

  return true
}

export async function connection(ws, req) {
  if (!req.session.term) {
    req.session.term = getContainerShell(req.session.container)
  }

  ws.on('message', message => {
    const decoded = message.toString()

    req.session.term.write(decoded)
  })

  req.session.term.onData(data => {
    ws.send(data)
  })

  req.session.term.onExit(exit => {
    ws.send(`Process terminated with code ${exit.exitCode}`)
    ws.close()
  })
}
