// NAT Punchthrough Server
// This server helps two chess clients find each other through NAT
// The server coordinates the punchthrough by having both clients
// connect to each other simultaneously

var json = use('json');
var waiting_client = null;
var match_id = 0;

$portal(e => {
  log.console("NAT server: received connection request");
  
  if (!is_actor(e.actor))
    send(e, {reason: "Must provide the actor you want to connect."});

  if (waiting_client) {
    log.console(`sending out messages! to ${e.actor} and ${waiting_client.actor}`)
    send(waiting_client, e.actor)
    send(e, waiting_client.actor)
    
    waiting_client = null
    
    return
  }
  
  waiting_client = e
  
  log.console(`actor ${e.actor} is waiting ...`)
}, 4000);
