import { runningContainers, startContainer } from './containers.js'
import bodyParser from 'body-parser'
import config from './config.js'
import express from 'express'
import cors from './cors.js'
import http from 'http'

export default (sessions) => {
  const app = express()

  app.use(bodyParser.json())

  if (config.dev) {
    cors(app)
  }

  app.get('/api/containers', async (req, res) => {
    return res.json(
      (await runningContainers())
        .map(c => ({ id: c.Id, image: c.Image, labels: c.Labels }))
    )
  })

  app.post('/api/containers', async (req, res) => {
    if ((req.body.image && typeof req.body.image !== 'string') || (req.body.cmd && Array.isArray(req.body.cmd))) {
      return res.send('invalid arguments').status(401)
    }

    const container = await startContainer(req.body.image, req.body.cmd)

    res.send(container)
  })

  app.post('/api/containers/:container/sessions/:session/resize', (req, res) => {
    const session = sessions[req.params.session]

    if (!session || session.container !== req.params.container) {
      return res.send('invalid session').status(401)
    }

    if (!req.body.cols || !req.body.rows) {
      return res.send('missing arguments').status(401)
    }

    session.term.resize(req.body.cols, req.body.rows)

    res.send('ok')
  })

  return http.createServer(app)
}
