import { WebSocketServer } from 'ws'
import { EDITOR_SESSION, TERMINAL_SESSION } from '../lib/SocketTypes.js'
import { upgrade as upgradeShell, connection as connectionShell  } from './shell.js'
import { upgrade as upgradeEditor, connection as connectionEditor } from './editor.js'

export default (server, sessions) => {
  const wss = new WebSocketServer({ noServer: true })

  server.on('upgrade', async (request, socket, head) => {
    const forbidden = () => {
      socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n')
      socket.destroy()
    }

    const path = request.url.substr(1).split('/')

    if (path.length < 1 || path[0] !== 'ws') {
      return forbidden()
    }

    if (path.length > 3 && path[1] === 'editor' && (await upgradeEditor(sessions, request, path))) {
      // /ws/editor/:project/:path
      request.type = EDITOR_SESSION

    } else if (path.length === 4 && path[1] === 'terminal' && (await upgradeShell(sessions, request, path))) {
      // /ws/terminal/:container/:session
      request.type = TERMINAL_SESSION

    } else {
      return forbidden()
    }

    wss.handleUpgrade(request, socket, head, ws => {
      wss.emit('connection', ws, request)
    })
  })

  wss.on('connection', async (ws, req) => {
    if (req.type === EDITOR_SESSION) {
      await connectionEditor(ws, req)
    }

    if (req.type === TERMINAL_SESSION) {
      await connectionShell(ws, req)
    }
  })
}
