// jamsh test-cluster.js


var workers = cluster({
  connect:true,
  rows:2,
  cols:2,
  port0:11001,
  port1:10001,
  portn:100,
  proto:['http','udp'],
  poll:2000,
  todo:'start()',
  verbose:1,
});
workers.start()


var loop=0;
later(2000,function () {
  // if (loop==3) workers.restart();
  // if (loop==6) workers.stop();
  print (workers.report());
  loop++;
  return true;
});

var p1=port(DIR.IP('udp://localhost:12000'));
later(500,function () {
  connect(DIR.IP('udp://localhost:10002'))
});

function walker(test) {
  this.next="init";
  this.goto=null;
  this.test=test;
  this.t0=0;
  this.hops=0;
  this.dirs=[DIR.EAST,DIR.SOUTH,DIR.WEST,DIR.NORTH];
  this.act = {
    init:function () { 
      this.t0=time();
      if (!this.test) { log('Starting on '+myNode()); log(myPosition()); }
      var next=link(DIR.IP('%'))
      if (next && next.length) this.goto=DIR.NODE(next[0]);
      if (!this.test) log(next)      
    },
    move: function () {
      this.hops++;
      if (!this.test) log('Going to '+this.goto);
      moveto(this.goto);
    },
    sense: function () {
      var next;
      if (!this.test) log('I am on '+myNode());
      next=this.dirs.shift();
      this.goto=next;
      if (!this.test) sleep(1000)
    },
    end: function () { log('END '+(time()-this.t0)+'ms '+this.hops+' hops'); kill() }
  }
  this.trans = {
    init:"move",
    move:"sense",
    sense:function () { return this.goto?"move":"end"  }
  }
}
later(3000,function () {
  create(walker,[true],2);
})

start();