const Client = require('../Client')
const {
  updateProfile
} = require('../../profile')

/**
 * WebPlayer class
 */
class WebPlayer extends Client {
  constructor (argv) {
    super(argv)
    const { features, permissions, expiresIn } = this.argv
    this.features = typeof features === 'string' && JSON.parse(features)
    this.permissions = typeof permissions === 'string' && JSON.parse(permissions)
    this.expiresIn = parseInt(expiresIn, 10)
  }

  /**
   * Create a Web Player session
   * @returns {Promise<Array<object>>}
   */
  createSession = async () => this._fetch('POST', 'v1/webplayer', {
    projectId: this.project,
    instanceId: this.instance,
    features: this.features,
    permissions: this.permissions ? this.permissions : null,
    expiresIn: this.expiresIn
  })

  /**
   * Destroy a Web Player session
   * @param {string} sessionId
   * @returns {Promise<{object}>}
   */
  destroySession = async (sessionId) => this._fetch('DELETE', `v1/webplayer/${sessionId}`, {})

  /**
   * List Web Player sessions
   * @returns {Promise<Array<object>>}
   */
  listSessions = async (sessionId) => {
    const path = sessionId ? `v1/webplayer/${sessionId}` : 'v1/webplayer'
    return this._fetch('GET', path, {})
  }

  /**
   * Log into WebPlayer session by activating WebPlayer credentials
   * @param {string} sessionId
   * @returns {Promise<void>}
   */
  login = async (sessionId) => {
    const { token, expiration } = (await this.listSessions()).filter(s => s.identifier === sessionId).shift()
    await updateProfile({ token, expiration, endpoint: this._profile.endpoint })
  }
}

module.exports = WebPlayer
