<commit_before>'use strict';

/**
 * handler.js
 *
 * This file contains a class that handles all the messages from server. Basically this handler will deliver messages
 * to proper handler(s) which will consume the message and make some magic stuff.
 */

/**#@+
 * Module dependencies
 *
 * @type {exports}
 */
var JSONStream = require('JSONStream');

/** @type {Level} */
var Level = require('./level');

/** @type {Karmes} */
var Karmes = require('./karmes');

/** @type {LoggerInstance} */
var Logger = require('./logger');
/**#@-*/

/**
 * Constructor of the Handler class. This constructor has three (3) main jobs.
 *  1) Create new 'Level' instance
 *  2) Create new 'Karmes' instance, and pass Level to it
 *  3) Register socket listeners
 *
 * @param   {Connection}  connection
 * @constructor
 */
function Handler(connection) {
  var _this = this;

  Logger.silly('Handler class initialized.');

  // Store connection
  _this.connection = connection;

  // Store player
  _this.player = connection.player;

  // Initialize new level and actual Kärmes!
  _this.level = new Level(_this.player);
  _this.karmes = new Karmes(_this.level, _this.connection);

  // Register socket event listeners
  _this._registerListeners();
}

/**
 * Method to join game.
 *
 * @returns {Boolean|*}
 */
Handler.prototype.joinGame = function joinGame() {
  var _this = this;

  Logger.info('Player: \'' + _this.player + '\' joined to game');

  // Join game
  return _this.connection.sendMessage({
    msg: 'join',
    data: {
      player: {
        name: _this.player
      }
    }
  });
};

/**
 * Private helper method to register all necessary socket event listeners from server. This will pipe all socket
 * messages from server to JSONStream parser, so we have proper JSON messages from server instead of pure stream.
 *
 * @private
 */
Handler.prototype._registerListeners = function _registerListeners() {
  var _this = this;

  Logger.info('Registering all handler listeners for socket messages...');

  // Create JSON stream of current socket connection
  var jsonStream = _this.connection.client.pipe(JSONStream.parse());

  // Yeah we got some data from server, so handle that
  jsonStream.on('data', function onData(data) {
    Logger.silly('Got \'data\' message', JSON.stringify(data));

    _this._handleMessage(data);
  });

  // Error event, this should not happen... :D
  jsonStream.on('error', function onData(data) {
    Logger.silly('Got \'error\' message', JSON.stringify(data));

    _this._handleError(data);
  });

  // Stream end handler
  jsonStream.on('end', function onData(data) {
    Logger.silly('Got \'end\' message', JSON.stringify(data));

    _this._handleEnd(data);
  });
};

/**
 * Method to handle specified message from server. Basically this will just route the message to 'Level' or 'Karmes'
 * classes which will do all necessary magic behind this bot.
 *
 * @param   {{}}  message Socket message to handle
 * @private
 */
Handler.prototype._handleMessage = function _handleMessage(message) {
  var _this = this;

  Logger.info('Game message: ' + message.msg, JSON.stringify(message.data));

  switch (message.msg) {
    case 'joined':
      break;
    case 'created':
      break;
    case 'start':
      _this.level.setGrid(message.data);
      break;
    case 'end':
      break;
    case 'positions':
      // Set players positions to level
      _this.level.setPlayers(message.data);

      // Calculate each paths for each snake
      _this.level.makePaths();

      // And then make a move!
      _this.karmes.makeMove();
      break;
    case 'apple':
      _this.level.setApple(message.data);
      break;
    default:
      Logger.error('Unknown message', JSON.stringify(message));
      break;
  }
};

/**
 * Private helper method to handle possible errors on socket stream.<commit_msg>Moved path calculation to right class.<commit_after>'use strict';

/**
 * handler.js
 *
 * This file contains a class that handles all the messages from server. Basically this handler will deliver messages
 * to proper handler(s) which will consume the message and make some magic stuff.
 */

/**#@+
 * Module dependencies
 *
 * @type {exports}
 */
var JSONStream = require('JSONStream');

/** @type {Level} */
var Level = require('./level');

/** @type {Karmes} */
var Karmes = require('./karmes');

/** @type {LoggerInstance} */
var Logger = require('./logger');
/**#@-*/

/**
 * Constructor of the Handler class. This constructor has three (3) main jobs.
 *  1) Create new 'Level' instance
 *  2) Create new 'Karmes' instance, and pass Level to it
 *  3) Register socket listeners
 *
 * @param   {Connection}  connection
 * @constructor
 */
function Handler(connection) {
  var _this = this;

  Logger.silly('Handler class initialized.');

  // Store connection
  _this.connection = connection;

  // Store player
  _this.player = connection.player;

  // Initialize new level and actual Kärmes!
  _this.level = new Level(_this.player);
  _this.karmes = new Karmes(_this.level, _this.connection);

  // Register socket event listeners
  _this._registerListeners();
}

/**
 * Method to join game.
 *
 * @returns {Boolean|*}
 */
Handler.prototype.joinGame = function joinGame() {
  var _this = this;

  Logger.info('Player: \'' + _this.player + '\' joined to game');

  // Join game
  return _this.connection.sendMessage({
    msg: 'join',
    data: {
      player: {
        name: _this.player
      }
    }
  });
};

/**
 * Private helper method to register all necessary socket event listeners from server. This will pipe all socket
 * messages from server to JSONStream parser, so we have proper JSON messages from server instead of pure stream.
 *
 * @private
 */
Handler.prototype._registerListeners = function _registerListeners() {
  var _this = this;

  Logger.info('Registering all handler listeners for socket messages...');

  // Create JSON stream of current socket connection
  var jsonStream = _this.connection.client.pipe(JSONStream.parse());

  // Yeah we got some data from server, so handle that
  jsonStream.on('data', function onData(data) {
    Logger.silly('Got \'data\' message', JSON.stringify(data));

    _this._handleMessage(data);
  });

  // Error event, this should not happen... :D
  jsonStream.on('error', function onData(data) {
    Logger.silly('Got \'error\' message', JSON.stringify(data));

    _this._handleError(data);
  });

  // Stream end handler
  jsonStream.on('end', function onData(data) {
    Logger.silly('Got \'end\' message', JSON.stringify(data));

    _this._handleEnd(data);
  });
};

/**
 * Method to handle specified message from server. Basically this will just route the message to 'Level' or 'Karmes'
 * classes which will do all necessary magic behind this bot.
 *
 * @param   {{}}  message Socket message to handle
 * @private
 */
Handler.prototype._handleMessage = function _handleMessage(message) {
  var _this = this;

  Logger.info('Game message: ' + message.msg, JSON.stringify(message.data));

  switch (message.msg) {
    case 'joined':
      break;
    case 'created':
      break;
    case 'start':
      _this.level.setGrid(message.data);
      break;
    case 'end':
      break;
    case 'positions':
      // Set players positions to level
      _this.level.setPlayers(message.data);

      // Calculate paths to apple
      _this.karmes.calculatePaths();

      // And then make a move!
      _this.karmes.makeMove();
      break;
    case 'apple':
      _this.level.setApple(message.data);
      break;
    default:
      Logger.error('Unknown message', JSON.stringify(message));
      break;
  }
};

/**
 * Private helper method to handle possible errors on socket stream.
{'fraction_non_alphanumeric': 0.130859375, 'fraction_numerical': 0.0010416666666666667, 'mean_word_length': 3.20415982484948, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '294755', 'n_tokens_mistral': 2259, 'n_tokens_neox': 2200, 'n_words': 714}