
const { readFile } = require('node:fs/promises')
const InstanceCLI = require('../../clients/Instance')
const { handleError } = require('../../error')
const chalk = require('chalk')

/**
 * Upload input to a device.
 *
 * @param yargs
 * @returns {Promise<void>}
 */
async function builder (yargs) {
  yargs
    .positional('instance', {
      type: 'string',
      demandOption: true,
      describe: 'virtual device id',
      default: process.env.INSTANCE
    })
    .positional('file', {
      type: 'string',
      demandOption: true,
      describe: 'JSON file of device inputs'
      // Input specification https://app.corellium.com/api/docs#post-/v1/instances/-instanceId-/input
    })
    .option('verbose', {
      alias: 'v',
      type: 'boolean',
      describe: 'console will receive verbose error output',
      default: false
    })
}

async function handler (argv) {
  const { file, verbose } = argv
  const client = new InstanceCLI(argv)
  try {
    const json = JSON.parse((await readFile(file)).toString())
    await client.input(json)
    console.log(chalk.green('Successfully uploaded inputs'))
  } catch (error) {
    handleError(error, 'input failed', verbose)
  }
}

module.exports = {
  builder,
  handler,
  command: 'input <instance> <file>',
  describe: 'Upload a series of inputs to a device.'
}
