import path from 'path'
import Koa from 'koa'
import koaStatic from 'koa-static'
import Router from 'koa-router'
import detect from 'detect-port'

class Server {
  app!: any
  router: any
  port: number
  constructor() {
    this.app = new Koa()
    this.router = new Router()
    this.port = 3000
  }

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

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

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

export default Server
