const Webplayer = require('../../clients/Webplayer')
const { displayTable } = require('../../table')
const { validateNonEmpty } = require('../../utils')
const { handleError } = 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: 'Webplayer Session ID',
    demandOption: false,
    string: true
  }).option('format', {
    type: 'input',
    describe: 'Output format (default is json) e.g. table',
    string: true,
    choices: ['table', '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) {
    handleError(err, 'List sessions failed', argv.verbose)
  }
}

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