const { getErrorMessage } = require('../../error')
const { displayTable } = require('../../table')
const { getApi } = require('../../utils')

async function builder (yargs) {
  yargs.option('verbose', {
    alias: 'v',
    type: 'boolean',
    describe: 'Console will receive verbose error output'
  }).option('project', {
    type: 'input',
    describe: 'Optionally filter by project name'
  }).option('format', {
    type: 'input',
    describe: 'Output format (default is table) e.g. json',
    string: true,
    choices: ['json', 'csv']
  })
}

async function handler (argv) {
  const api = await getApi()
  try {
    let instances
    if (argv.project) {
      instances = await api.v1GetProjectInstances(argv.project, {})
    } else {
      instances = await api.v1GetInstances()
    }
    if (!instances.length && argv.format !== 'json') {
      console.error('Found no matching Instances')
    }
    await displayTable(argv.format, instances, [
      'id', 'flavor', 'type', 'state', 'os'
    ], [{ column: 3, width: 5 }, { column: 2, width: 4 }, { column: 1, width: 6 }])
  } catch (error) {
    const errorMessage = getErrorMessage(error)
    console.error(`List failed: ${errorMessage}`)

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

module.exports = {
  builder,
  handler,
  command: 'list',
  describe: 'List instances'
}
