package jetbrains.jetpad.model.event;

import jetbrains.jetpad.base.Registration;
import jetbrains.jetpad.model.collections.CollectionItemEvent;
import jetbrains.jetpad.model.collections.list.ObservableList;
import jetbrains.jetpad.model.property.Selector;

import java.util.ArrayList;
import java.util.List;

public class EventSources {
  @SafeVarargs
  public static <EventT> EventSource<EventT> composite(EventSource<? extends EventT>... sources) {
    return new CompositeEventSource<>(sources);
  }

  public static <EventT, ItemT> EventSource<EventT> selectList(final ObservableList<ItemT> list, final Selector<ItemT, EventSource<? extends EventT>> selector) {
    return new EventSource<EventT>() {
      @Override
      public Registration addHandler(final EventHandler<? super EventT> handler) {
        final List<Registration> itemRegs = new ArrayList<>();
        for (ItemT item : list) {
          itemRegs.add(selector.select(item).addHandler(handler));
        }


        final Registration listReg = list.addHandler(new EventHandler<CollectionItemEvent<? extends ItemT>>() {
          @Override
          public void onEvent(CollectionItemEvent<? extends ItemT> event) {
            if (event.isAdded()) {
              itemRegs.add(event.getIndex(), selector.select(event.getItem()).addHandler(handler));
            } else {
              itemRegs.remove(event.getIndex()).remove();
            }
          }
        });


        return new Registration() {
          @Override
          protected void doRemove() {
            for (Registration r : itemRegs) {
              r.remove();
            }

            listReg.remove();
          }
        };
      }
    };
  }
}

@@ -75,16 +75,77 @@
 ration;%0A
+import jetbrains.jetpad.model.collections.CollectionAdapter;%0A
 import j
@@ -1084,70 +1084,45 @@
 .add
-Handl
+Listen
 er(new 
-EventHandler%3CCollectionItemEvent%3C? extends 
+CollectionAdapter%3C
 ItemT%3E
-%3E
 () %7B
@@ -1166,21 +1166,25 @@
  void on
-Event
+ItemAdded
 (Collect
@@ -1226,45 +1226,8 @@
 ) %7B%0A
-            if (event.isAdded()) %7B%0A  
     
@@ -1334,21 +1334,113 @@
     
-  %7D else
+%7D%0A%0A          @Override%0A          public void onItemRemoved(CollectionItemEvent%3C? extends ItemT%3E event)
  %7B%0A
-  
     
@@ -1491,30 +1491,16 @@
 move();%0A
-            %7D%0A
         

Use collection listeners instead of raw handlers where possible