const { getErrorMessage } = require('../../error')
const asciiArt = require('ascii-art')
const { getApi, sleep } = 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 delete to complete',
      demandOption: false
    })
}

async function handler (argv) {
  const api = await getApi()
  const instanceId = argv.instanceId
  try {
    await api.v1DeleteInstance(instanceId)
    if (argv.wait) {
      let remaining
      do {
        await sleep(1000)
        const instances = await api.v1GetInstances()
        remaining = instances.find((i) => i.id === instanceId)
      } while (remaining)
    }
    console.log(
      asciiArt.style(`Successfully deleted instance ${instanceId}`, 'green', true)
    )
  } catch (error) {
    const errorMessage = getErrorMessage(error)
    console.error(`Failed to delete ${instanceId}: ${errorMessage}`)

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

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