const { handleError } = require('../../error')
const chalk = require('chalk')
const { waitForState } = require('../../utils')
const InstanceCLI = require('../../clients/Instance')

async function builder (yargs) {
  yargs.positional('instanceId', {
    type: 'string',
    describe: 'Instance id',
    demandOption: true
  })
    .option('verbose', {
      alias: 'v',
      type: 'boolean',
      describe: 'Console will receive verbose error output'
    })
    .option('wait', {
      type: 'boolean',
      describe: 'Wait for the instance to be fully started'
    })
    .option('paused', {
      type: 'boolean',
      describe: 'Start instance in a paused state'
    })
    .option('sockcap', {
      type: 'boolean',
      describe: 'Start sockcap add-on if loaded'
    })
}

async function handler (argv) {
  const { sockcap, paused } = argv
  const instance = new InstanceCLI(argv)
  try {
    await instance.start({ sockcap, paused })
    if (argv.wait) {
      // Wait 60 attempts for the instance to be created (5 minutes)
      await waitForState(argv.instanceId, instance.info.bind(instance), 'on', 60)
    }
    console.log(
      chalk.green(`Successfully started instance ${argv.instanceId}`)
    )
  } catch (err) {
    handleError(err, `Failed to start ${argv.instance}`, argv.verbose)
  }
}

module.exports = {
  builder,
  handler,
  command: 'start <instanceId> [--wait] [--verbose] [--paused] [--sockcap]',
  describe: 'Start instance'
}
