const AgentCLI = require('./Agent')
const { displayTable } = require('../../table')
const { validateNonEmpty } = require('../../utils')
const { getErrorMessage } = require('../../error')
const log = require('../../logging')

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

async function handler (argv) {
  try {
    const agent = new AgentCLI(argv)
    const files = await agent.listFiles()
    await displayTable(argv.format, files, ['name', 'size'])
  } catch (err) {
    const errorMessage = getErrorMessage(err)
    log.error(`List files failed: ${errorMessage}`)
    if (argv.detailedErrors) { log.error(err) }
  }
}

module.exports = {
  builder,
  handler,
  command: 'files',
  describe: 'List files on device instance'
}
