package dvi.event;

public class TEventMulticaster
implements TEventListener
{
  protected final TEventListener a, b;

  protected TEventMulticaster(TEventListener a, TEventListener b)
  {
    this.a = a;
    this.b = b;
  }

  public static TEventListener add(TEventListener a, TEventListener b)
  {
    if (a == null) return b;
    if (b == null) return a;
    return new TEventMulticaster(a, b);
  }

  public static TEventListener remove(TEventListener a, TEventListener b)
  {
    if (a == null || a == b) {
      return null;
    } else if (a instanceof TEventMulticaster) {
      return ((TEventMulticaster) a).remove(b);
    } else {
      return a;
    }
  }

  public void handleEvent(TEvent e)
  {
    a.handleEvent(e);
    b.handleEvent(e);
  }

  public String toString()
  {
    if (a == null) return b.toString();
    if (b == null) return a.toString();
    return "(" + a.toString() + "," + b.toString() + ")";
  }

  protected TEventListener remove(TEventListener o)
  {
    if (o == a) return b;
    if (o == b) return a;
    TEventListener a2 = remove(a, o);
    TEventListener b2 = remove(b, o);
    if (a2 == a && b2 == b) {
      return this;
    }
    return add(a2, b2); 
  }
}
