import assert from './assert'

export default function wrapActions(observer, arg, wrapRecursively = false) {
  assert(typeof observer === 'object' && typeof observer.next === 'function',
    'Expected observer to be an object containing at least a next method.')

  const transform = fn => (...args) => observer.next(fn(...args))
  const wrap = input => {
    if (typeof input === 'function') {
      return transform(input)
    }

    if (Array.isArray(input)) {
      return input.map(x => {

        if (wrapRecursively) {
          return wrap(x)
        }

        assert(typeof x === 'function', 'Expected array to contain exclusively functions. Did you intend to use wrapActions recursively?')
        return transform(x)
      })
    }

    if (typeof input === 'object') {
      return Object.keys(input).reduce((prev, key) => {
        if (input.hasOwnProperty(key)) {
          const x = input[key]

          if (wrapRecursively) {
            prev[key] = wrap(x)
          } else {
            assert(typeof x === 'function', 'Expected object to contain exclusively functions.')
            prev[key] = transform(x)
          }
        }

        return prev
      }, {})
    }

    throw new Error('Expected either an action creator or an array/object containing some as arguments.')
  }

  return wrap(arg)
}


@@ -338,21 +338,34 @@
  wrap = 
+(
 input
+, keys = %5B%5D)
  =%3E %7B%0A  
@@ -493,17 +493,24 @@
 put.map(
-x
+(x, key)
  =%3E %7B%0A%0A 
@@ -558,24 +558,42 @@
 eturn wrap(x
+, keys.concat(key)
 )%0A        %7D%0A
@@ -600,32 +600,43 @@
 %0A        assert(
+%0A          
 typeof x === 'fu
@@ -647,107 +647,129 @@
 on',
- 'Expected array to contain exclusively functions. Did you intend to use wrapActions recursively?')
+%0A          %60wrapActions: Expected a %5C%60function%5C%60$%7Bkeys.length ? ' in' + keys.toString() : ''%7D but got %5C%60$%7Btypeof x%7D%5C%60.%60)%0A
 %0A   
@@ -1038,16 +1038,34 @@
 = wrap(x
+, keys.concat(key)
 )%0A      
@@ -1092,24 +1092,39 @@
      assert(
+%0A              
 typeof x ===
@@ -1139,61 +1139,133 @@
 on',
- 'Expected object to contain exclusively functions.')
+%0A              %60wrapActions: Expected a %5C%60function%5C%60$%7Bkeys.length ? ' in' + keys.toString() : ''%7D but got %5C%60$%7Btypeof x%7D%5C%60.%60)%0A
 %0A   
@@ -1385,92 +1385,116 @@
 ror(
-'Expected either an action creator or an array/object containing some as arguments.'
+%60wrapActions: Expected a %5C%60function%5C%60$%7Bkeys.length ? ' in' + keys.toString() : ''%7D but got %5C%60$%7Btypeof x%7D%5C%60.%60
 )%0A  

Improve wrapActions error messages