const log = require('../../../logging')
const InstanceCLI = require('../../../clients/Instance')

async function builder (yargs) {
  yargs
    .positional('instanceId', {
      type: 'string',
      describe: 'Instance id',
      demandOption: true
    })
    .option('srcPorts', {
      type: 'array',
      describe: 'Source ports to filter'
    })
    .option('dstPorts', {
      type: 'array',
      describe: 'Destination ports to filter'
    })
    .option('ports', {
      type: 'array',
      describe: 'Source or destination ports to filter'
    })
    .option('processes', {
      type: 'array',
      describe: 'List of process names or pids to filter'
    })
    .option('portRanges', {
      type: 'array',
      describe: 'List of port ranges in that format \'[beginPort]-[endport]\''
    })
    .option('protocols', {
      type: 'array',
      describe: 'List of protocols'
    })
    .option('verbose', {
      alias: 'v',
      type: 'boolean',
      describe: 'Console will receive verbose error output',
      demandOption: false
    })
}

async function handler (argv) {
  try {
    const { srcPorts, dstPorts, ports, processes, portRanges, protocols } = argv

    const instance = new InstanceCLI(argv)
    await instance.enableMonitoring({
      srcPorts, dstPorts, ports, processes, portRanges, protocols
    })
    log.info('Success')
  } catch (e) {
    if (e.response) {
      log.error(`${e.response.status} ${e.response.data.error || e.response.statusText}`)
    } else {
      if (e.message) {
        log.error(e.message)
      } else {
        log.error('Urecognized error, use --verbose for details')
      }
    }

    if (argv.verbose) { log.error(JSON.stringify(e)) }
    process.exit(1)
  }
}

module.exports = {
  builder,
  handler,
  command: 'enable <instanceId> [--verbose]',
  describe: 'Enable network monitoring'
}
