const AgentCLI = require('../../../clients/Agent')
const { displayTable } = require('../../../table')
const { validateNonEmpty } = require('../../../utils')
const { handleError } = require('../../../error')
const InstallCommand = require('./install')

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('load-icons', {
    type: 'input',
    describe: 'Toggle loading of icons',
    demandOption: false,
    boolean: true
  }).option('format', {
    type: 'input',
    describe: 'Output format (default is json) e.g. table',
    string: true,
    choices: ['table', 'json', 'csv']
  }).command(InstallCommand)
}

async function handler (argv) {
  try {
    const { loadIcons } = argv
    const agent = new AgentCLI(argv)
    const apps = (await agent.listApps({ loadIcons })) || []
    if (apps) { await displayTable(argv.format, apps, ['name', 'bundleID']) }
  } catch (err) {
    handleError(err, 'List apps failed', argv.verbose)
  }
}

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