const WebPlayer = require('./WebPlayer')
const log = require('../../logging')
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: 'WebPlayer Session ID',
    demandOption: true,
    string: true,
    validateNonEmpty
  })
}

async function handler (argv) {
  const { session: sessionId } = argv
  try {
    const webplayer = new WebPlayer(argv)
    await webplayer.login(sessionId)
    log.info(`Login to Web Player session ${sessionId} successful`)
  } catch (err) {
    const errorMessage = getErrorMessage(err)
    log.error(`Login to Web Player session ${sessionId} failed: ${errorMessage}`)
    if (argv.detailedErrors) {
      log.error(err)
    }
  }
}

module.exports = {
  builder,
  handler,
  command: 'login',
  describe: 'Log CLI into a web player session'
}
