const path = require('path')
const Koa = require('koa')
const koaStatic = require('koa-static')
const router = require('koa-router')()
const detect = require('detect-port')

class Server {
  constructor() {
    this.app = new Koa()
    this.router = router
    this.port = 3000
  }

  async launch() {
    const publicPath = path.resolve(__dirname, '../assets')
    this.app.use(router.routes()).use(koaStatic(publicPath))

    return new Promise((resolve, reject) => {
      detect(this.port)
        .then((_port) => {
          if (this.port !== _port) {
            console.log(`端口: ${this.port} 已被占用, 尝试新端口: ${_port}`)
            this.port = _port
          }

          this.app.listen(this.port, () => {
            resolve()
          })
        })
        .catch((err) => {
          console.log(err)
          reject()
        })
    })
  }
}

module.exports = Server
