const ip = require('ip')
const path = require('path')
const detect = require('detect-port')
const del = require('del')
const config = require('./lib/config')
const devtool = require('./lib/index')
const env = require('./lib/util/env')

const defaultConfig = {}
defaultConfig.port = '8088'
defaultConfig.loglevel = 'error'
defaultConfig.remotedebugport = config.REMOTE_DEBUG_PORT

// Get the local environment
env.getVersionOf('weex', v => {
  config.weexVersion = v && v.version
})
env.getVersionOf('npm', v => {
  config.npmVersion = v && v.version
})
env.getVersionOf('node', v => {
  config.nodeVersion = v && v.version
})

// Formate config
config.ip = ip.address()
config.ext = 'vue'

// process.on('uncaughtException', (err) => {
//   try {
//     let killTimer;
//     const params = Object.assign({
//       stack: err && err.stack,
//       os: os.platform(),
//       node: config.nodeVersion,
//       npm: config.npmVersion
//     }, config.weexVersion);
//     killTimer = setTimeout(function () {
//       process.exit(1);
//     }, 30000);
//     killTimer.unref();
//   } catch (e) {
//     logger.error('Error Message: ', e.stack);
//   }
// });

// process.on('unhandledRejection', (reason, p) => {logger
//   const params = Object.assign({
//     stack: reason,
//     os: os.platform(),
//     node: config.nodeVersion,
//     npm: config.npmVersion
//   }, config.weexVersion);
//   logger.error(reason);
//   if (/simctl error/.test(reason)) {
//     logger.warn(`The simulator debug need Xcode environment, you can run \`simctl --version\` to check if you have the correct environment.`);
//   }
//   else if (/Chromium revision is not downloaded/.test(reason)) {
//     logger.warn(`You may not have installed chromium properly, you can find solution here https://github.com/weexteam/weex-toolkit/issues/275.`);
//   }
// });

// process.on('SIGINT', err => {
//   headless.closeHeadless();
//   exit(0);
// })

function execute(target) {
  // Check whether the port is occupied
  detect(defaultConfig.port).then(open => {
    config.inUse = open !== +defaultConfig.port
    if (config.inUse) {
      config.inUse = {
        old: defaultConfig.port,
        open: open
      }
      config.port = open
    } else {
      config.port = defaultConfig.port
    }
    try {
      del.sync(
        path.join(__dirname, '../frontend/', config.BUNDLE_DIRECTORY, '/*'),
        {
          force: true
        }
      )
    } catch (e) {}
    devtool.start(target, config)
  })
}

exports.execute = execute
