'use strict';

import io from 'socket.io';

export default class ServerToolListner {
  constructor(server) {
    this.server = server;
  }

  listen(port) {
    let server = this.server;
    this.serverTool = io.listen(port);
    this.serverTool.on('connection', function(socket) {
      console.log('tool connected');

      socket.on('players', (option, callback) => {
        callback(server.getCurrentListAuthorizedPlayers());
        socket.disconnect(false);
      });
      socket.on('syncdb', async (option, callback) => {
        let response = await server.updatePlayersFromDb();
        callback(response);
        socket.disconnect(false);
      });

      socket.on('add-player', async (username, callback) => {
        let response = await server.addPlayerDb(...username);
        callback(response);
        socket.disconnect(false);
      });
      socket.on('remove-player', async (username, callback) => {
        let response = await server.removePlayerDb(...username);
        callback(response);
        socket.disconnect(false);
      });

      socket.on('add-game', async (game, callback) => {
        let response = '';
        try {
          response = await server.addGameDb(...game);
          response = 'OK - inserted at id :' + response;
        } catch (err) {
          response = 'KO ' + err.message;
        }
        callback(JSON.stringify(response));
        socket.disconnect(false);
      });
      socket.on('remove-game', async (options, callback) => {
        let response = await server.removeGameDb(...options);
        callback(response);
        socket.disconnect(false);
      });
    });
  }
}
