'use strict';

const WebSocket = require('ws');
const program = require('commander');

const common = require('../server/common');

// node coral/coralClient.js --host localhost --port 8081 --name coral --number 10

program
  .version('0.0.1')
  .option('-h, --host [fqdn||ip]', 'userGarden host')
  .option('-p, --port <n>', 'userGarden port', parseInt)
  .option('-nm, --name [name]', 'name of Corals')
  .option('-n, --number <n>', 'number of Corals', parseInt)
  .parse(process.argv);


if (require.main === module) {
  console.log(program.host);
  console.log(program.port);
  console.log(program.name);
  console.log(program.number);

  var coralsPool = [];

  for (let i = 0; i < program.number; i++) {

    let socket = new WebSocket(`ws://${program.host}:${program.port}/`);
    let coralLogin = `${program.name}${i}`;

    coralsPool.push(socket);

    socket.onopen = function () {
      const login = coralLogin;
      socket.send(JSON.stringify({'login': login}));
      console.log('Connection done.');

      setInterval(() => {
        const directions = ['up', 'down', 'left', 'right'];
        const d = directions[common.getRandomInt(0, 3)];
        socket.send(JSON.stringify({'login': login, 'direction': d}));

      }, 500);
    };

    socket.onmessage = function (event) {
      const rawMessage = event.data;
      console.log('Data received: ' + rawMessage.length);
    };

    socket.onclose = function (event) {
      if (event.wasClean) {
        console.log('Connection closed.');
      } else {
        console.log('Connection broken.'); // for example, server died
      }
      console.log('Code: ' + event.code + ' reason: ' + event.reason);
    };

    socket.onerror = function (error) {
      console.log('Error ' + error.message);
    };

  }

}

@@ -1238,19 +1238,49 @@
   %7D, 500
+ + common.getRandomInt(0, 400)
 );%0A
-
     %7D;%0A%0A
@@ -1366,27 +1366,26 @@
       co
-nsole
+mmon
 .log(
-'
+%60
 Data rec
@@ -1389,22 +1389,34 @@
 received
-: ' + 
+ $%7BcoralLogin%7D: $%7B
 rawMessa
@@ -1424,16 +1424,18 @@
 e.length
+%7D%60
 );%0A    %7D
@@ -1664,19 +1664,17 @@
 log(
-'
+%60
 Code: 
-' + 
+$%7B
 even
@@ -1683,12 +1683,9 @@
 code
- + '
+%7D
  rea
@@ -1689,20 +1689,18 @@
 reason: 
-' + 
+$%7B
 event.re
@@ -1703,16 +1703,18 @@
 t.reason
+%7D%60
 );%0A    %7D
@@ -1778,19 +1778,17 @@
 log(
-'
+%60
 Error 
-' + 
+$%7B
 erro
@@ -1796,16 +1796,18 @@
 .message
+%7D%60
 );%0A    %7D

Add random delay. Improve logging.