//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE

package tripleplay.ui;

import java.util.HashMap;
import java.util.Map;

import react.Connection;
import react.Signal;
import react.Slot;

public class Selector
{
    public Signal<Element<?>> selected = Signal.create();
    public Signal<Element<?>> deselected = Signal.create();

    public Selector (Elements<?> elements) {
        for (Element<?> child : elements) {
            onChildAdded(child);
        }
        elements.childAdded.connect(new Slot<Element<?>> () {
            @Override public void onEmit (Element<?> added) {
                onChildAdded(added);
            }
        });
        elements.childRemoved.connect(new Slot<Element<?>> () {
            @Override public void onEmit (Element<?> removed) {
                _connections.remove(removed).disconnect();
            }
        });

    }

    public void setSelected (Element<?> selected) {
        if (_selected != null) {
            _selected.set(Element.Flag.SELECTED, false);
            _selected.invalidate();
            deselected.emit(_selected);
        }
        _selected = selected;
        _selected.set(Element.Flag.SELECTED, true);
        _selected.invalidate();
        this.selected.emit(_selected);
    }

    public Element<?> selected () {
        return _selected;
    }

    protected void onChildAdded (Element<?> child) {
        if (child instanceof ClickableTextWidget) {
            _connections.put(child, ((ClickableTextWidget<?>)child).clicked.connect(_clickSlot));
        }
    }

    protected Element<?> _selected;

    protected final Slot<Element<?>> _clickSlot = new Slot<Element<?>>() {
        @Override public void onEmit (Element<?> clicked) {
            setSelected(clicked);
        }
    };

    protected final Map<Element<?>, Connection> _connections =
        new HashMap<Element<?>, Connection>();
}

@@ -937,22 +937,16 @@
    _conn
-ection
 s.remove
@@ -965,24 +965,24 @@
 sconnect();%0A
+
             
@@ -995,17 +995,16 @@
     %7D);%0A
-%0A
     %7D%0A%0A 
@@ -1013,20 +1013,24 @@
  public 
-void
+Selector
  setSele
@@ -1054,24 +1054,76 @@
 selected) %7B%0A
+        if (_selected == selected) %7B return this; %7D%0A
         if (
@@ -1312,24 +1312,61 @@
 = selected;%0A
+        if (_selected != null) %7B%0A    
         _sel
@@ -1405,32 +1405,36 @@
  true);%0A        
+  
+  
 _selected.invali
@@ -1433,32 +1433,42 @@
 d.invalidate();%0A
+        %7D%0A
         this.sel
@@ -1486,24 +1486,45 @@
 _selected);%0A
+        return this;%0A
     %7D%0A%0A    p
@@ -1709,22 +1709,16 @@
    _conn
-ection
 s.put(ch
@@ -2082,25 +2082,11 @@
 conn
-ections =%0A       
+s =
  new

Return this on setSelected