const Webplayer = require('../../clients/Webplayer')
const log = require('../../logging')
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: 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 Webplayer session ${sessionId} successful`)
  } catch (err) {
    handleError(err, `Login to Webplayer session ${sessionId} failed`, argv.verbose)
  }
}

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