const chalk = require('chalk')
const ngrok = require('ngrok')
const { hostname } = require('os')

const port = process.env.PORT || process.env.npm_package_config_nuxt_port || 3000
let host = process.env.HOST || process.env.npm_package_config_nuxt_host || 'localhost'
if (host === '0.0.0.0') {
  host = hostname()
}

// https://github.com/bubenshchykov/ngrok

module.exports = async function nuxtNgrok(options) {
  // Only include on dev mode
  if (!this.options.dev) {
    return
  }

  let connectedUrl = null

  let opts = {
    proto: 'http', // http|tcp|tls
    addr: `${host}:${port}`, // port or network address
  }

  if (options && Object.keys(options).length) {
    opts = Object.assign({}, opts, options)
  }

  this.nuxt.hook('build:done', async () => {
    if (!connectedUrl) {
      try {
        const url = await ngrok.connect(opts)
        connectedUrl = url
        console.log('\n' + chalk.bgGreen.black(' OPEN ') + chalk.green(` ${connectedUrl} for external access\n`))
      } catch (err) {
        return console.error('[nuxt][ngrok] ' + err)
      }
    }
    connectedUrl &&
      console.log('\n' + chalk.bgGreen.black(' OPEN ') + chalk.green(` ${connectedUrl} for external access\n`))
  })

  this.nuxt.hook('close', () => {
    ngrok.disconnect()
    connectedUrl &&
      console.log('\n' + chalk.bgGreen.black(' CLOSED NGROK '))
  })
}

module.exports.meta = require('./package.json')

@@ -620,58 +620,8 @@
  %7D%0A%0A
-  if (options && Object.keys(options).length) %7B%0A  
   op
@@ -653,20 +653,36 @@
 ts, 
+this.
 options
-)%0A  %7D
+.ngrok, options)
 %0A%0A  

handle ngrok options correctly (#223)