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

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('features', {
    type: 'input',
    describe: 'Enabled Feature Set',
    demandOption: true,
    string: true,
    validateNonEmpty
  }).option('permissions', {
    type: 'input',
    describe: 'Endpoint Permissions',
    demandOption: false,
    string: true,
    validateNonEmpty
  }).option('expiresIn', {
    type: 'input',
    describe: 'Token expiration in seconds',
    demandOption: true,
    string: true,
    validateNonEmpty
  }).option('format', {
    type: 'input',
    describe: 'Output format (default is json)',
    string: true,
    choices: ['json', 'csv']
  })
}

async function handler (argv) {
  try {
    const webplayer = new WebPlayer(argv)
    const session = await webplayer.createSession()
    // log.info('Created web player session')
    await displayTable(argv.format || 'json', [session], ['identifier', 'token', 'expiration', 'features'])
  } catch (err) {
    const errorMessage = getErrorMessage(err)
    log.error(`Create web player session failed: ${errorMessage}`)
    if (argv.detailedErrors) { log.error(err) }
  }
}

module.exports = {
  builder,
  handler,
  command: 'create',
  describe: 'Create a web player session returning the URL and token'
}
