import http from 'http'
import https from 'https'

export default class HttpServer {
  constructor(config) {
    this.ishttps = false
    this.active = null
    this.sockets = new Set()
    this.creator = http
    if (config && config.https) {
      this.creator = https
      this.ishttps = true
    }
  }

  createServer(opts, listener) {
    let server = this.creator.createServer(opts, listener)

    server.on('connection', (socket) => {
      this.sockets.add(socket)

      socket.once('close', () => {
        this.sockets.delete(socket)
      })
    })

    server.listenAsync = (port, host) => {
      return new Promise((res, rej) => {
        server.once('error', rej)

        server.listen(port, host || '::', () => {
          server.off('error', rej)
          res()
        })
      })
    }

    this.active = server
    return server
  }

  closeServer() {
    if (!this.active) return Promise.resolve()

    return new Promise((res, rej) => {
      this.sockets.forEach(function(socket) {
        socket.destroy()
      })
      this.sockets.clear()

      this.active.close(err => {
        if (err) {
          if (err.code !== 'ERR_SERVER_NOT_RUNNING') return rej(err)
        }
        this.active = null

        // Waiting 1 second for it to close down
        setTimeout(function() {res() }, 100)
      })
    })
  }
}
