'use strict'
var Emitter = require('../../../emitter')
var Base = require('../../../base')
var setKey = Base.prototype.setKey

var pattern = new Base({
  properties: {
    _stamp: true,
    _ignore: true,
    $condition: true,
    $any: true
  },
  define: {
    serialize () {
      var obj = {}
      var property
      for (var i in this) {
        if (i[0] !== '_') {
          if (i !== 'key') {
            property = this[i]
            let value = property._input
            obj[i] = property.serialize
              ? property.serialize()
              : property
            if (value) {
              obj[i].val = value
            }
          }
        } else if (i === '_childSub') {
          property = this[i]._input
          obj.$any = property.serialize
            ? property.serialize()
            : property
          obj._emitProperty = true
        }
      }
      return property ? obj : true
    },
    setKey (key, val, event, nocontext, escape) {
      if (key === 'parent') {
        return setKey.call(this, '$parent', val, event, nocontext, escape)
      } else if (key === 'key') {
        return setKey.call(this, '$key', val, event, nocontext, escape)
      }
      return setKey.apply(this, arguments)
    }
  },
  ChildConstructor: 'Constructor'
})

module.exports = new Emitter({
  emitInstances: false,
  properties: {
    pattern: pattern,
    cnt: 0
  },
  inject: [
    require('../run'),
    require('../field'),
    require('../object'),
    require('../upward'),
    require('../findemit'),
    require('../condition')
  ],
  define: {
    generateConstructor () {
      return function derivedBase (val, event, parent, key) {
        Base.apply(this, arguments)
        if (parent && !parent[key]) {
          this.subField(false, void 0, parent.parent, this.pattern, 1, { val: true }, {})
        }
      }
    },
    emitInternal (data, event, bind, key, trigger, ignore) {
      var dataStorage
      if (data && bind) {
        let bound = this.getBound(event, bind)
        dataStorage = bound && bound.data
        if (!dataStorage) {
          this.setBind(event, bind, (dataStorage = []), true)
        }
        dataStorage.push(data)
      }
      return Emitter.prototype
        .emitInternal.call(this, dataStorage, event, bind, key, trigger, ignore)
    }
  }
}).Constructor

@@ -588,16 +588,35 @@
 f (value
+ && obj%5Bi%5D !== true
 ) %7B%0A    
@@ -1395,20 +1395,8 @@
 tern
-,%0A    cnt: 0
 %0A  %7D

fix in pattern serialize