import startsWith from 'lodash.startswith'
import JsonRpcWebSocketClient, {
  OPEN,
  CLOSED
} from 'jsonrpc-websocket-client'
import { BaseError } from 'make-error'

// ===================================================================

const noop = () => {}

// ===================================================================

export class XoError extends BaseError {}

// -------------------------------------------------------------------

// TODO: implement call(...).retry(predicate)
export default class Xo extends JsonRpcWebSocketClient {
  constructor (opts) {
    const url = opts && opts.url || '.'
    super(`${url === '/' ? '' : url}/api/`)

    this._credentials = opts && opts.credentials || null
    this._user = null

    this.on(OPEN, () => {
      if (this._credentials) {
        this._signIn(this._credentials).catch(noop)
      }
    })
    this.on(CLOSED, () => {
      this._user = null
    })
  }

  get user () {
    return this._user
  }

  call (method, args, i) {
    if (startsWith(method, 'session.')) {
      return Promise.reject(
        new XoError('session.*() methods are disabled from this interface')
      )
    }

    const promise = super.call(method, args)
    promise.retry = (predicate) => promise.catch((error) => {
      i = (i || 0) + 1
      if (predicate(error, i)) {
        return this.call(method, args, i)
      }
    })

    return promise
  }

  signIn (credentials) {
    // Register this credentials for future use.
    this._credentials = credentials

    return this._signIn(credentials)
  }

  _signIn (credentials) {
    return super.call('session.signIn', credentials).then((user) => {
      this._user = user
      this.emit('authenticated')
    })
  }
}

@@ -446,54 +446,8 @@
 --%0A%0A
-// TODO: implement call(...).retry(predicate)%0A
 expo

remove irrelevant comment