import Ember from "ember";

var computed = Ember.computed;
var get = Ember.get;

var flatten = function (array) {
  return array.reduce(function (a, b) {
    return a.concat(b);
  });
};

var recursivelyFindByType = function (typeClass, children) {
  var view = children.find(function (view) {
    return typeClass.detectInstance(view);
  });

  if (view) {
    return view;
  }

  var childrenOfChildren = flatten(children.getEach('childViews'));
  if (childrenOfChildren.length === 0) {
    return null;
  }
  return recursivelyFindByType(typeClass, childrenOfChildren);
};

export default function(type) {
  return computed('childViews.[]', function nearestChild() {
    var typeClass = this.container.lookupFactory('component:' + type) ||
                    this.container.lookupFactory('view:' + type);

    return recursivelyFindByType(typeClass, get(this, 'childViews') || []);
  });
}

@@ -52,16 +52,43 @@
 mputed;%0A
+var bind = Ember.run.bind;%0A
 var get 
@@ -100,16 +100,16 @@
 er.get;%0A
-
 %0Avar fla
@@ -197,24 +197,28 @@
 ncat(b);%0A  %7D
+, %5B%5D
 );%0A%7D;%0A%0Avar r
@@ -629,24 +629,61 @@
 ion(type) %7B%0A
+  var tracking = Ember.Map.create();%0A
   return com
@@ -727,16 +727,19 @@
 stChild(
+key
 ) %7B%0A    
@@ -882,77 +882,695 @@
     
-return recursivelyFindByType(typeClass, get(this, 'childViews') %7C%7C %5B%5D
+var children = get(this, 'childViews') %7C%7C %5B%5D;%0A    var appendedChildren = children.filterBy('_state', 'inDOM');%0A    var detachedChildren = children.filter(function (child) %7B%0A      return %5B'inBuffer', 'hasElement', 'preRender'%5D.indexOf(child._state) !== -1;%0A    %7D);%0A%0A    appendedChildren.forEach(function (child) %7B%0A      tracking.delete(child);%0A    %7D);%0A%0A    var notifyChildrenChanged = bind(this, 'notifyPropertyChange', key);%0A    detachedChildren.forEach(function (child) %7B%0A      if (!tracking.has(child)) %7B%0A        child.one('didInsertElement', this, notifyChildrenChanged);%0A        tracking.set(child, true);%0A      %7D%0A    %7D);%0A%0A    return recursivelyFindByType(typeClass, appendedChildren
 );%0A 

make nearestChild aware of whether a child is appended