// Remote single stepping using RPC (worker)
// jamsh test-singlestep1.js -- 9001 
// 9002 9003 ...

var N = 1000, C= 10000,  verbose=0;
function ac(options) {
  this.options=options;
  this.sensor=null;
  this.loops=options.loops;
  this.act = {
    start: function () {
      log('Starting .. '+this.options.msg)
    },
    percept: function () {
      rd.try(0,['SENSOR',_],function (t) {
        if (t) this.sensor=t[1];
      })
    },
    action : function () {
      if (this.options.verbose || (this.loops%1000)==0) log(this.loops,this.sensor);
    },
    stop: function () {
      log('Terminating ..')
      kill()
    }
  }
  
  this.trans = {
    start:"percept",
    percept: function () { 
      if (this.sensor!=null) return "action";
      else return "stop";
    },
    action: function () {
      return (this.loops--)==0?"stop":"percept";
    },
  }
  this.next="start";
}
var sensor = 0;
provider(function (pat) {
  switch (pat[0]) {
    case 'SENSOR':
      return [pat[0],sensor];
      break;
  }
});
var agents=[];
for(var i=0;i<N;i++) {
  var ag = create(ac,{
    loops:C,
    msg:'with pace '+i,
    verbose:0
  },2);
  agents.push(ag);
}

Rpc.getreq('udp://localhost:'+(args[0]||9000),function (req,src) {
  switch (req.command) {
    case 'step':
      if (verbose) log('Step')
      step(1,true);
      return {status:'Ok'}
      break;
    case 'sensor':
      sensor = req.value;
      break;
  }
},{verbose:1})

start0();

