module.exports = update

var merge = require('lodash/merge')
var clone = require('lodash/clone')

var Promise = require('lie')

var internals = module.exports.internals = {}
internals.deserialise = require('../utils/deserialise')
internals.request = require('../utils/request')
internals.saveAccount = require('../utils/save-account')
internals.serialise = require('../utils/serialise')

function update (state, options) {
  if (!options) {
    return Promise.reject(new Error('Please specify an account property to update.'))
  }

  return internals.request({
    method: 'PATCH',
    url: state.url + '/session/account',
    headers: {
      authorization: 'Bearer ' + state.account.session.id
    },
    body: internals.serialise('account', options, state.account.id)
  })

  .then(function () {
    return internals.request({
      url: state.url + '/session',
      method: 'PUT',
      body: internals.serialise('session', options)
    })
  })

  .then(function (response) {
    var data = internals.deserialise(response.body, {
      include: 'account'
    })
    state.account.session.id = data.id

    merge(state.account, options)
    internals.saveAccount({
      cacheKey: state.cacheKey,
      account: state.account
    })

    state.emitter.emit('update', clone(state.account))

    return state.account
  })

  .catch(function (error) {
    if (error.statusCode === 401) {
      state.account.session.invalid = true
      state.emitter.emit('unauthenticate')

      internals.saveAccount({
        cacheKey: state.cacheKey,
        account: state.account
      })
    }

    throw error
  })
}

@@ -18,16 +18,52 @@
 update%0A%0A
+var clone = require('lodash/clone')%0A
 var merg
@@ -90,29 +90,28 @@
 merge')%0Avar 
-clone
+omit
  = require('
@@ -117,21 +117,20 @@
 'lodash/
-clone
+omit
 ')%0A%0Avar 
@@ -509,16 +509,9 @@
 or('
-Please s
+S
 peci
@@ -542,17 +542,16 @@
 o update
-.
 '))%0A  %7D%0A
@@ -818,318 +818,357 @@
 on (
-) %7B%0A    return internals.request(%7B%0A      url: state.url + '/session',%0A      method: 'PUT',%0A      body: internals.serialise('session', options)%0A    %7D)%0A  %7D)%0A%0A  .then(function (response) %7B%0A    var data = internals.deserialise(response.body, %7B%0A      include: 'account'%0A    %7D)%0A    state.account.session.id = data.id
+response) %7B%0A    // when a username changes, the session ID gets recalculated, as it%E2%80%99s based%0A    // on the username, see npm.im/couchdb-calculate-session-id. In that case%0A    // the server sets x-set-session with the new session id.%0A    if (response.headers%5B'x-set-session'%5D) %7B%0A      state.account.session.id = response.headers%5B'x-set-session'%5D%0A    %7D
 %0A%0A  
@@ -1190,23 +1190,43 @@
 ccount, 
+omit(
 options
+, %5B'password'%5D)
 )%0A    in

set session ID from `x-set-session` response header