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('session', {
    type: 'input',
    describe: 'Web Player Session ID',
    demandOption: false,
    string: true
  }).option('format', {
    type: 'input',
    describe: 'Output format (default is table) e.g. json',
    string: true,
    choices: ['json', 'csv']
  })
}

async function handler (argv) {
  try {
    const webplayer = new WebPlayer(argv)
    const result = await webplayer.listSessions(argv.session)
    if (!result.length && argv.format !== 'json') {
      console.error('Found no matching Webplayer sessions')
    }
    const sessions = (await webplayer.listSessions(argv.session)).map(s => {
      const {
        identifier,
        token,
        expiration,
        features
      } = s
      return {
        identifier,
        token,
        expiration,
        features
      }
    })
    await displayTable(argv.format, sessions, ['identifier', 'token', 'expiration', 'features'])
  } catch (err) {
    const errorMessage = getErrorMessage(err)
    log.error(`List sessions failed: ${errorMessage}`)
    if (argv.detailedErrors) {
      log.error(err)
    }
  }
}

module.exports = {
  builder,
  handler,
  command: 'list',
  describe: 'List web player sessions for a project'
}
