/**
 *
 * User: Martin Donnelly
 * Date: 2016-09-07
 * Time: 15:33
 *
 */

var url = require('url');
var logger = require('log4js').getLogger();


module.exports = function(events, wsServer) {
  'use strict';

  wsServer.on('connection', function connection(ws) {
    var location = url.parse(ws.upgradeReq.url, true);

    logger.info('Creating event for this connection');

    logger.info((new Date()) + ' Connection accepted.');

    var sendSocketHandler = (obj) => {
        logger.debug('sendSocketHandler', obj);
        try {
          ws.send(JSON.stringify(obj));
        }
        catch (err) {
          logger.error(err);
          logger.warn('Offending object: ', obj);
        }
      };

    events.on('sendSocket', sendSocketHandler);

    ws.on('message', function(message) {
        console.log('received:', message);

      if (message === 'update') {
        events.emit('update');
      }
      });

    ws.on('close', function(reasonCode, description) {
      logger.info((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
      events.removeListener('sendSocket', sendSocketHandler);
    });

  });



  return module;
};
