package modules.gossip;

import utils.*;
import simulator.*;
import modules.region.*;
import java.lang.reflect.*;
import java.util.*;

/* 
   Gossip, like broadcast, fills an area with information. Gossip,
   however, is centerless. Rather, a Gossip item merges data from
   all sources is the region, spreading it omnidirectionally through
   neighbors.
*/

public class VersionGossip extends Observable implements Gossip {
  VersionedData d = new VersionedData();
  public Object get() { return d.get(); }
  public void set(Object o) 
  { d.incrementVersion(); d.set(o); setChanged(); notifyObservers(); }

  // copy data from a neighbor in
  public void integrate(Gossip nbr, PortedProcessor pp) {
    if(!(nbr instanceof VersionGossip)) return;
    VersionGossip n = (VersionGossip)nbr;
    Object old = get();
    d.merge(n.d);
    if(get()!=old) { setChanged(); notifyObservers(); }
  }
  public void update(PortedProcessor pp) {}
  // must be a deep clone
  public Object clone() { 
    VersionGossip vg = new VersionGossip();
    vg.d.setVersion(d.getVersion());
    vg.d.setQuality(d.getQuality());
    // brute force cloning technology
    Object data = d.get();
    try {
      Method c = data.getClass().getMethod("clone",new Class[]{});
      vg.d.set(c.invoke(data,new Object[]{}));
    } catch(Exception e) {
      vg.d.set(data);
    }
    return vg;
  }
  public String toString() {
    return "(VG "+d+")";
  }
}
