'use strict';

// process.exit(1);
var usage = function() {
  var text = `
    USAGE : npm run tools <option>
      with <option> :
       - players : get authorized players
       - add-player <username> : Add a new authorized player
       - remove-player <username> : Remove an authorized player
       - syncdb : Force server to sync with db
       - add-game <json>: Add new game into DB
          '{"player1":"","player2":"","deck":"","advRules":[],"status":"","data":"{}"}'
            deck     : faction tournament draft  (one of these)
            advRules : popularity discard        (0 or any of these)
            status   : CREATED ONGOING FINISHED  (one of these)
       - remove-game <method> <filter> : Remove game(s) from DB
          <method>          /  <filter>
            byId                 gameId
            byPlayer1            username
            byPlayerAny          username
            byStatus             CREATED ONGOING FINISHED  (one of these)
            byDays               number of days old is last connection
            finishedByDays       number of days old is last connection(only finished)
       `;
  console.log(text);
};

var args = process.argv.slice(2);

if (args.length === 0) {
  usage();
  process.exit(0);
}
var command = '';
var option = '';
switch (args[0]) {
  case 'players':
  case 'syncdb':
    command = args[0];
    break;

  case 'add-player':
  case 'remove-player':
  case 'add-game':
  case 'remove-game':
    if (args[0] === 'remove-game' && args.length < 3) {
      usage();
      process.exit(0);
    }
    if (args[1] && args[1] !== '') {
      command = args[0];
      if (args[0] === 'add-game') {
        try {
          option = [JSON.parse(args[1])];
        } catch (error) {
          console.log(error);
          process.exit(0);
        }
      } else {
        args.shift();
        option = args;
      }
    } else {
      console.log('error ; specify a username');
      usage();
    }
    break;

  default:
    usage();
    break;
}

if (command !== '') {
  console.log('Connecting to server...');
  var socket = require('socket.io-client')('http://localhost:1664');
  socket.emit(command, option, function(response) {
    console.log('Done, response from server : ', response);
  });
}
