'use strict'

const bufferapp = require('buffer-node')
const CONFIG = require('config').buffer
const {each, waterfall} = require('async')
const {get} = require('lodash')

const compose = require('./compose')
const {accounts, access_token} = CONFIG

const accessToken = get(global, access_token)
const client = bufferapp(accessToken)

function createUpdate (doc, cb) {
  const text = compose(doc)
  return client.updates.create(text, accounts).nodeify(cb)
}

const createUpdates = (docs, cb) => each(docs, createUpdate, cb)
const shuffleAccount = (account, cb) => client.profile(account).updates.shuffle().nodeify(cb)
const shuffle = (cb) => each(accounts, shuffleAccount, cb)

function share (docs, cb) {
  const tasks = [
    (next) => createUpdates(docs, next),
    (res, next) => shuffle(next)
  ]
  return waterfall(tasks, cb)
}

module.exports = share

@@ -448,20 +448,35 @@
 ify(
-cb)%0A%7D%0A%0Aconst
+err =%3E cb(err))%0A%7D%0A%0Afunction
  cre
@@ -485,18 +485,16 @@
 eUpdates
- =
  (docs, 
@@ -493,26 +493,34 @@
  (docs, cb) 
-=%3E
+%7B%0A  return
  each(docs, 
@@ -533,29 +533,35 @@
 Update, cb)%0A
-const
+%7D%0A%0Afunction
  shuffleAcco
@@ -563,18 +563,16 @@
 eAccount
- =
  (accoun
@@ -578,18 +578,26 @@
 nt, cb) 
-=%3E
+%7B%0A  return
  client.
@@ -643,35 +643,66 @@
 ify(
-cb)%0Aconst shuffle = (cb) =%3E
+err =%3E cb(err))%0A%7D%0A%0Afunction shuffleUpdates (cb) %7B%0A  return
  eac
@@ -732,16 +732,18 @@
 unt, cb)
+%0A%7D
 %0A%0Afuncti
@@ -832,13 +832,8 @@
    (
-res, 
 next
@@ -844,16 +844,23 @@
  shuffle
+Updates
 (next)%0A 

Fix share callback