
var _ = require('lodash');
var requestIp = require('request-ip');
var bodyParser = require('body-parser-json');
var uuid = require('uuid');
var request = require('request');

var $Peer = require('./peer');

const DEFAULTPORT = 9338;

exports.middleware = function(app) {
    app.use(requestIp.mw());
    app.use(bodyParser.json());
    return function(req, res, next) {
        var peerData = {};
        peerData.id = req.body.id || uuid.v4();
        peerData.ip = req.body.ip || req.clientIp;
        peerData.port = req.body.port || DEFAULTPORT;
        peerData.data = req.body.data || {};
        var otherPeers = _.clone(app.peers);
        app.peers.push(new $Peer(peerData));
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({
            status: 'joined',
            self: {
                id: app.id,
                data: app.options.data
            },
            peers: otherPeers
        }));
    };
};

exports.method = function(peers, options, cb) {
    var self = this;
    if(!peers.length)
        return cb({code: 'NOPEERSFOUND'});
    request({
        method: 'POST',
        json: true,
        timeout: 1000,
        url: 'http://' + peers[0].ip + ':' + peers[0].port + '/join',
        body: _.assign({}, self.options, options)
    }, function(err, res, body) {
        if(err || body.status != 'joined')
            return self.join(peers.slice(1), options, cb);
        self.peers = body.peers.map(function(peerData) {
            return new $Peer(peerData);
        });
        self.peers.push(new $Peer({
            id: body.self.id,
            ip: peers[0].ip,
            port: peers[0].port,
            data: body.self.data
        }));
        cb(null);
    });
};


@@ -1026,16 +1026,47 @@
 = this;%0A
+    if(!options) options = %7B%7D;%0A
     if(!
@@ -1286,16 +1286,145 @@
    body:
+ %7B%0A            id: self.id,%0A            ip: options.ip %7C%7C self.options.ip %7C%7C null,%0A            port: self.port,%0A            data:
  _.assig
@@ -1441,16 +1441,21 @@
 .options
+.data
 , option
@@ -1455,17 +1455,32 @@
  options
-)
+.data)%0A        %7D
 %0A    %7D, 

send correct peer data when joining