'use strict';

const debug = require('abacus-debug')('abacus-healthchecker');
const edebug = require('abacus-debug')('е-abacus-healthchecker');

const { iindex } = require('abacus-vcapenv');

// Interleave health-checks between application instances
const refreshIntervalMs = () => 2000 + iindex() * 1500;

const isEmpty = function(obj) {
  return Object.keys(obj).length === 0;
};

module.exports = async(applicationGroups, applicationHealthClient, applicationsUrisBuilder) => {

  const getApplicationsStatuses = async(appsUris) => {
    const groupStatuses = {};
    for(let uri of appsUris) {
      const appStatus = await applicationHealthClient.getApplicationHealth(uri);
      groupStatuses[uri] = appStatus;
    }
    return groupStatuses;
  };

  const getApplicationsHealth = async() => {
    const result = {};

    try {
      await Promise.all(Object.keys(applicationGroups).map(async(groupName) => {
        const applicationsCount = applicationGroups[groupName];
        const appsUris = await applicationsUrisBuilder.buildUris(groupName, applicationsCount);
        result[groupName] = await getApplicationsStatuses(appsUris);
      }));
    } catch (e) {
      edebug('Error while getting applications health. Error: ', e);
      throw e;
    }

    return result;
  };

  let applicationsHealth = {};
  const scheduleApplicationHealthRefresh = async() => {
    setTimeout(async() => {
      debug('Refreshing applications health...');
      applicationsHealth = await getApplicationsHealth();
      debug('New applications health status: %j', applicationsHealth);
      scheduleApplicationHealthRefresh();
    }, refreshIntervalMs());
  };

  if (!isEmpty(applicationGroups)) {
    applicationsHealth = await getApplicationsHealth();
    scheduleApplicationHealthRefresh();
  }

  return {
    getSystemHealth: () => {
      return applicationsHealth;
    }
  };

};

@@ -279,9 +279,9 @@
  =%3E 
-2
+5
 000 
@@ -297,9 +297,9 @@
 ) * 
-1
+3
 500;
@@ -1287,53 +1287,21 @@
 %0A%0A  
-let applicationsHealth = %7B%7D;%0A  const schedule
+const refresh
 Appl
@@ -1313,23 +1313,16 @@
 onHealth
-Refresh
  = async
@@ -1333,38 +1333,8 @@
 %3E %7B%0A
-    setTimeout(async() =%3E %7B%0A  
     
@@ -1381,30 +1381,25 @@
 ');%0A    
-  applications
+const app
 Health =
@@ -1430,18 +1430,16 @@
 alth();%0A
-  
     debu
@@ -1485,41 +1485,130 @@
  app
-licationsHealth);%0A      scheduleA
+Health);%0A    return appHealth;%0A  %7D;%0A%0A  let applicationsHealth = %7B%7D;%0A%0A  const scheduleAppHealthRefresh = async() =%3E %7B%0A    a
 ppli
@@ -1617,30 +1617,91 @@
 tion
+s
 Health
-Refresh();%0A    %7D
+ = await refreshApplicationHealth();%0A    setTimeout(scheduleAppHealthRefresh
 , re
@@ -1764,70 +1764,18 @@
 ps))
- %7B
 %0A    a
-pplicationsHealth = await getApplicationsHealth();%0A   
+wait
  sch
@@ -1782,24 +1782,16 @@
 eduleApp
-lication
 HealthRe
@@ -1798,20 +1798,16 @@
 fresh();
-%0A  %7D
 %0A%0A  retu

Refactor healthchecker