// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var allocCluster = require('../lib/test-cluster.js');
var collectParallel = require('collect-parallel/array');
var CountedReadySignal = require('ready-signal/counted');

allocCluster.test('dead exit peers get reaped', {
    size: 10,
    namedRemotes: ['alice', 'alice', 'alice', 'alice', 'alice', 'alice', 'alice']
}, function t(cluster, assert) {
    var i;
    var alice;
    var serviceProxy;
    var app;

    // Verify that hyperban is connected to all the alices
    for (i = 0; i < cluster.namedRemotes.length; i++) {
        alice = cluster.namedRemotes[i];
        cluster.checkExitPeers(assert, {
            serviceName: alice.serviceName,
            hostPort: alice.hostPort
        });
    }

    // Reap peers that have not registered (nobody)
    for (i = 0; i < cluster.apps.length; i++) {
        app = cluster.apps[i];
        serviceProxy = app.clients.serviceProxy;
        serviceProxy.reapPeers();
    }

    // Verify that all alices are still connected
    for (i = 0; i < cluster.namedRemotes.length; i++) {
        alice = cluster.namedRemotes[i];
        cluster.checkExitPeers(assert, {
            serviceName: alice.serviceName,
            hostPort: alice.hostPort
        });
    }

    // Some of the peers re-register
    var activeNum = 3;
    var ready = CountedReadySignal(activeNum);
    for (i = 0; i < activeNum; i++) {
        alice = cluster.namedRemotes[i];
        cluster.sendRegister(alice.channel, {
            serviceName: alice.serviceName
        }, ready.signal);
    }
    ready(afterReRegister);

    function afterReRegister(err) {
        if (err) {
            assert.end(err);
            return;
        }

        reapClusterPears(cluster, assert, afterReapPeers);
    }

    function afterReapPeers() {

        // Some of the peers remain
        for (i = 0; i < activeNum; i++) {
            alice = cluster.namedRemotes[i];
            cluster.checkExitPeers(assert, {
                serviceName: alice.serviceName,
                hostPort: alice.hostPort,
                isDead: false // NOT DEAD YET
                // I FEEL HAPPY
            });
        }
        // Others not so much
        for (i = activeNum; i < cluster.namedRemotes.length; i++) {
            alice = cluster.namedRemotes[i];
            cluster.checkExitPeers(assert, {
                serviceName: alice.serviceName,
                hostPort: alice.hostPort,
                isDead: true
            });
        }

        // But then everybody registers again!
        ready = CountedReadySignal(cluster.namedRemotes.length);
        for (i = 0; i < cluster.namedRemotes.length; i++) {
            alice = cluster.namedRemotes[i];
            cluster.sendRegister(alice.channel, {
                serviceName: alice.serviceName
            }, ready.signal);
        }
        ready(afterResurrection);
    }

    function afterResurrection(err) {
        if (err) {
            assert.end(err);
            return;
        }

        // Verify that all the peers have rejoined the fray.
        for (i = 0; i < cluster.namedRemotes.length; i++) {
            alice = cluster.namedRemotes[i];
            cluster.checkExitPeers(assert, {
                serviceName: alice.serviceName,
                hostPort: alice.hostPort
            });
        }

        // And they all lived happily ever after.
        // The end.
        assert.end();

    }

});

function reapClusterPears(cluster, assert, callback) {
    collectParallel(
        cluster.apps,
        function reapEach(app, i, done) {
            var serviceProxy = app.clients.serviceProxy;
            serviceProxy.reapPeers(done);
        },
        function finish(_, results) {
            for (var i = 0; i < results.length; i++) {
                var res = results[i];
                assert.ifError(res.err, 'no error from reaping app ' + i);
            }
            callback();
        }
    );
}

@@ -1517,33 +1517,21 @@
 var 
-serviceProxy;%0A    var app
+activeNum = 3
 ;%0A%0A 
@@ -1886,173 +1886,98 @@
     
-for (i = 0; i %3C cluster.apps.length; i++) %7B%0A        app = cluster.apps%5Bi%5D;%0A        serviceProxy = app.clients.serviceProxy;%0A        serviceProxy.reapPeers();
+reapClusterPears(cluster, assert, initialReapDone);%0A%0A    function initialReapDone() %7B
 %0A    
-%7D%0A%0A
     
@@ -2022,24 +2022,28 @@
 nnected%0A    
+ 
+   
 for (i = 0; 
@@ -2082,32 +2082,36 @@
  i++) %7B%0A        
+    
 alice = cluster.
@@ -2127,32 +2127,36 @@
 tes%5Bi%5D;%0A        
+ 
+   
 cluster.checkExi
@@ -2176,32 +2176,36 @@
 , %7B%0A            
+    
 serviceName: ali
@@ -2224,32 +2224,36 @@
 me,%0A            
+ 
+   
 hostPort: alice.
@@ -2253,32 +2253,36 @@
  alice.hostPort%0A
+    
         %7D);%0A    
@@ -2277,27 +2277,35 @@
     %7D);%0A    
-%7D%0A%0A
+    %7D%0A%0A    
     // Some 
@@ -2333,35 +2333,16 @@
 ter%0A    
-var activeNum = 3;%0A
     var 
@@ -2380,16 +2380,20 @@
 veNum);%0A
+    
     for 
@@ -2422,32 +2422,36 @@
  i++) %7B%0A        
+    
 alice = cluster.
@@ -2459,32 +2459,36 @@
 amedRemotes%5Bi%5D;%0A
+    
         cluster.
@@ -2521,32 +2521,36 @@
 , %7B%0A            
+    
 serviceName: ali
@@ -2564,32 +2564,36 @@
 iceName%0A        
+   
+ 
 %7D, ready.signal)
@@ -2598,22 +2598,30 @@
 l);%0A    
-%7D%0A
+    %7D%0A   
     
+ 
 ready(af
@@ -2635,16 +2635,22 @@
 gister);
+%0A    %7D
 %0A%0A    fu
@@ -3604,24 +3604,28 @@
 in!%0A        
+var 
 ready = Coun

use reapClusterPeers for initial reap