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

async function builder (yargs) {
  yargs
    .option('verbose', {
      alias: 'v',
      type: 'boolean',
      describe: 'Console will receive verbose error output'
    })
    .option('format', {
      type: 'input',
      describe: 'Output format (default is table) e.g. json',
      string: true,
      choices: ['json', 'csv']
    })
    .positional('flavor', {
      type: 'string',
      describe: 'Flavor',
      demandOption: true
    })
    .positional('os', {
      type: 'string',
      describe: 'Operating system',
      demandOption: true
    })
    .positional('project', {
      type: 'string',
      describe: 'Project ID to associate with instance',
      demandOption: true
    })
    .option('name', {
      type: 'string',
      describe: 'Optional name of instance',
      demandOption: false
    })
    .option('wait', {
      type: 'boolean',
      describe: 'Wait for the instance to be ready',
      demandOption: false
    })
}

async function handler (argv) {
  const flavor = argv.flavor
  const os = argv.os
  const project = argv.project
  const name = argv.name
  const api = await getApi()

  try {
    const instance = await api.v1CreateInstance({ flavor, os, project, name })
    // Wait 360 attempts for the instance to be created (30 minutes)
    if (argv.wait) {
      await waitForState(instance.id, api.v1GetInstance.bind(api), 'on', 360)
    }
    console.log(instance.id)
  } catch (error) {
    const errorMessage = getErrorMessage(error)
    console.error(`Failed to create instance: ${errorMessage}`)

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

module.exports = {
  builder,
  handler,
  command: 'create <flavor> <os> <project> [name] [wait]',
  describe: 'Create instance and associate with a project'
}
