const Client = require('../../clients/Client')
const { handleError } = require('../../error')
const log = require('../../logging')
const { getMastApiBasePath } = require('./api-base-path')

/**
 * The start-monitor command starts device monitoring via the start-monitor API on corellium-mast
 *
 * @param yargs
 * @returns {Promise<void>}
 */
async function builder (yargs) {
  yargs
    .option('assessment', {
      alias: 'a',
      type: 'string',
      describe: 'MATRIX assessment id',
      demandOption: true
    })
    // NOTE: only required due to coordinator proxy needing to authenticate access to instance
    .option('instance', {
      alias: 'i',
      type: 'string',
      demandOption: true,
      describe: 'virtual device id',
      default: process.env.INSTANCE
    })
    .option('verbose', {
      alias: 'v',
      type: 'boolean',
      describe: 'Console will receive verbose error output',
      default: false
    })
}

async function handler (argv) {
  const { assessment, instance, verbose } = argv
  const client = new Client(argv)
  try {
    const API_BASE_PATH = await getMastApiBasePath(client, instance)
    await client._fetch('POST', `${API_BASE_PATH}/${instance}/assessments/${assessment}/start`)
    log.info('Monitoring started.')
  } catch (error) {
    handleError(error, 'start-monitor failed', verbose)
  }
}

module.exports = {
  builder,
  handler,
  command: 'start-monitor',
  describe: 'Start device monitoring for assessment'
}
