<commit_before>var querystring = require('querystring');
var PeerClient = require('../peer_client');
var rels = require('zetta-rels');
var MediaType = require('api-media-type');
var Query = require('calypso').Query;
var http = require('http');

var PeerManagementResource = module.exports = function(server) {
  this.server = server;
  this.registry = server.peerRegistry;
};

PeerManagementResource.prototype.init = function(config) {
  config
    .path('/peer-management')
    .produces(MediaType.SIREN)
    .consumes(MediaType.FORM_URLENCODED)
    .get('/', this.list)
    .post('/', this.link)
    .get('/{id}', this.show)
    .del('/{id}', this.deletePeer)
};

PeerManagementResource.prototype.list = function(env, next) {
  var allQuery = Query.of('peers');

  this.registry.find(allQuery, function(err, results) {
    var builder = new PeerManagementBuilder(results, env.helpers.url);
    env.response.body = builder.build();
    next(env);
  });

};

PeerManagementResource.prototype.link = function(env, next) {
  var self = this;

  env.request.getBody(function(err, body) {
    if (err) {
      env.response.statusCode = 400;
      return next(env);
    }

    var query = querystring.parse(body.toString());

    self.server._peers.push(query.url);

    var peer = {
      url: query.url,
      direction: 'initiator',
      status: 'connecting'
    }; 

    self.registry.add(peer, function(err, peer) {
      if (err) {
        env.response.statusCode = 500;
        return next(env);
      }

      self._connect(peer);

      env.response.statusCode = 202;
      env.response.setHeader('Location', env.helpers.url.join(peer.id));

      next(env);
    });
  });
};

//This is conditonal based on where the request is coming from.
//From acceptor we'll add additonal info to the request, and proxy to initiator
//From intiator we'll perform the disconnection
PeerManagementResource.prototype.deletePeer = function(env, next) {
  var id = env.route.params.id;
  var self = this;
  this.registry.get(id, function(err, result) {
    if(result.direction === 'initiator') {
      var wsUrl = PeerClient.calculatePeerUrl(result.url, self.server._name);
      var peers = self.server._peerClients.filter(function(peer) {
        return peer.url === wsUrl;  
      });
      var client = peers[0];
      env.response.statusCode = 200;
      next(env);
      client.close();     

    } else if(result.direction === 'acceptor') {
      var socket = self.server.httpServer.peers[id];
      socket.on('end', function() {
        env.response.statusCode = 200;
        next(env);  
      });
      //self.server.httpServer.proxyToPeer(env, next); 
      var peer = self.server.httpServer.peers[id];
      var req = env.request;
      var res = env.response;
      var agent = env.zettaAgent || peer.agent;

      var opts = { method: req.method, headers: req.headers, path: req.url, agent: agent };
      var request = http.request(opts);
      request.end();
    } else {
      env.response.statusCode = 500;
      next(env);  
    }  
  });
};

PeerManagementResource.prototype.updatePeer = function(env, next) {};
<commit_msg>Refactoring for the update API action.<commit_after>var querystring = require('querystring');
var PeerClient = require('../peer_client');
var rels = require('zetta-rels');
var MediaType = require('api-media-type');
var Query = require('calypso').Query;
var http = require('http');

var PeerManagementResource = module.exports = function(server) {
  this.server = server;
  this.registry = server.peerRegistry;
};

PeerManagementResource.prototype.init = function(config) {
  config
    .path('/peer-management')
    .produces(MediaType.SIREN)
    .consumes(MediaType.FORM_URLENCODED)
    .get('/', this.list)
    .post('/', this.link)
    .get('/{id}', this.show)
    .del('/{id}', this.deletePeer)
};

PeerManagementResource.prototype.list = function(env, next) {
  var allQuery = Query.of('peers');

  this.registry.find(allQuery, function(err, results) {
    var builder = new PeerManagementBuilder(results, env.helpers.url);
    env.response.body = builder.build();
    next(env);
  });

};

PeerManagementResource.prototype.link = function(env, next) {
  var self = this;

  env.request.getBody(function(err, body) {
    if (err) {
      env.response.statusCode = 400;
      return next(env);
    }

    var query = querystring.parse(body.toString());

    self.server._peers.push(query.url);

    var peer = {
      url: query.url,
      direction: 'initiator',
      status: 'connecting'
    }; 

    self.registry.add(peer, function(err, peer) {
      if (err) {
        env.response.statusCode = 500;
        return next(env);
      }

      self._connect(peer);

      env.response.statusCode = 202;
      env.response.setHeader('Location', env.helpers.url.join(peer.id));

      next(env);
    });
  });
};

//This is conditonal based on where the request is coming from.
//From acceptor we'll add additonal info to the request, and proxy to initiator
//From intiator we'll perform the disconnection
PeerManagementResource.prototype.deletePeer = function(env, next) {
  var id = env.route.params.id;
  var self = this;
  this.registry.get(id, function(err, result) {
    if(result.direction === 'initiator') {
      self._disconnect(result);
      env.response.statusCode = 200;
      next(env);
    } else if(result.direction === 'acceptor') {
      self._proxyDisconnect(env, next);
    } else {
      env.response.statusCode = 500;
      next(env);  
    }  
  });
};

PeerManagmentResource.prototype._disconnect = function(peer) {
  var wsUrl = PeerClient.calculatePeerUrl(result.url, self.server._name);
  var peers = self.server._peerClients.filter(function(peer) {
    return peer.url === wsUrl;  
  });
  var client = peers[0];
  client.close();     
  };

PeerManagementResource.prototype._proxyDisconnect = function(env, next) { 
  var socket = self.server.httpServer.peers[id];
  socket.on('end', function() {
    env.response.statusCode = 200;
    next(env);  
  });
  //self.server.httpServer.proxyToPeer(env, next); 
  var peer = self.server.httpServer.peers[id];
  var req = env.request;
  var res = env.response;
  var agent = env.zettaAgent || peer.agent;

  var opts = { method: req.method, headers: req.headers, path: req.url, agent: agent };
  var request = http.request(opts);
  request.end();
 
};

PeerManagementResource.prototype.updatePeer = function(env, next) {};

{'fraction_non_alphanumeric': 0.14811936586882188, 'fraction_numerical': 0.005906123717749456, 'mean_word_length': 3.203135205747877, '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': '4652187', 'n_tokens_mistral': 2104, 'n_tokens_neox': 2016, 'n_words': 425}