const { getErrorMessage } = require('../../error')
const asciiArt = require('ascii-art')
const { getApi, waitForState } = require('../../utils')

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 stopped'
    })
}

async function handler (argv) {
  const api = await getApi()
  const instanceId = argv.instanceId
  try {
    await api.v1StopInstance(instanceId)
    if (argv.wait) {
      // Wait 60 attempts for the instance to be created (5 minutes)
      await waitForState(instanceId, api.v1GetInstance.bind(api), 'off', 60)
    }
    console.log(
      asciiArt.style(`Successfully stopped instance ${instanceId}`, 'green', true)
    )
  } catch (error) {
    const errorMessage = getErrorMessage(error)
    console.error(`Failed to stop ${instanceId}: ${errorMessage}`)

    if (argv.detailedErrors) {
      console.log(error)
    }
  }
}

module.exports = {
  builder,
  handler,
  command: 'stop <instanceId> [wait]',
  describe: 'Stop instance'
}
