import has from 'lodash/has';
import isSchema from './util/isSchema';

class Conditional {

  constructor(refs, options) {
    let { is, then, otherwise } = options;

    this.refs = [].concat(refs)

    if (typeof options === 'function')
      this.fn = options
    else
    {
      if (!has(options, 'is'))
        throw new TypeError('`is:` is required for `when()` conditions')

      if (!options.then && !options.otherwise)
        throw new TypeError(
          'either `then:` or `otherwise:` is required for `when()` conditions'
        )

      let isFn = typeof is === 'function'
        ? is : ((...values) => values.every(value => value === is))

      this.fn = function (...values) {
        let ctx = values.pop();
        return isFn(...values) ? ctx.concat(then) : ctx.concat(otherwise)
      }
    }
  }

  getValue(parent, context) {
    let values = this.refs.map(r => r.getValue(parent, context))

    return values
  }

  resolve(ctx, values) {
    let schema = this.fn.apply(ctx, values.concat(ctx))

    if (schema !== undefined && !isSchema(schema))
      throw new TypeError('conditions must return a schema object')

    return schema || ctx
  }
}

export default Conditional;

@@ -64,16 +64,143 @@
 hema';%0A%0A
+function callOrConcat(schema) %7B%0A  if (typeof schema === 'function')%0A    return schema%0A%0A  return base =%3E base.concat(schema)%0A%7D%0A%0A
 class Co
@@ -320,16 +320,89 @@
 (refs)%0A%0A
+    then = callOrConcat(then);%0A    otherwise = callOrConcat(otherwise);%0A%0A
     if (
@@ -905,18 +905,28 @@
    let c
-tx
+urrentSchema
  = value
@@ -942,22 +942,28 @@
         
-return
+let option =
  isFn(..
@@ -977,47 +977,61 @@
 ) ? 
-ctx.concat(
 then
-)
  : 
-ctx.concat(otherwise
+otherwise%0A%0A        return option(currentSchema
 )%0A  

allow function then/otherwise bodies