var
  q = require('q'),
  os = require('os'),
  _ = require('lodash'),
  BadRequestError = require('../core/errors/badRequestError'),
  ResponseObject = require('../core/models/responseObject'),
  internalIndex = require('rc')('kuzzle').internalIndex;

module.exports = function ReadController (kuzzle) {
  this.search = function (requestObject) {
    kuzzle.pluginsManager.trigger('data:search', requestObject);

    return kuzzle.services.list.readEngine.search(requestObject);
  };

  this.get = function (requestObject) {
    kuzzle.pluginsManager.trigger('data:get', requestObject);

    return kuzzle.services.list.readEngine.get(requestObject);
  };

  this.count = function (requestObject) {
    kuzzle.pluginsManager.trigger('data:count', requestObject);

    return kuzzle.services.list.readEngine.count(requestObject);
  };

  this.listCollections = function (requestObject, context) {
    var
      type = requestObject.data.body.type || 'all',
      realtimeCollections;

    var filterCollections = (response, collectionType) => {
      var rightsRequest = {
          action: 'listCollections',
          controller: 'read',
          index: requestObject.index
        },
        allowedCollections = [];

      response.data.body.collections[collectionType].forEach(collection => {
        rightsRequest.collection = collection;

        if (context.token.user.profile.isActionAllowed(rightsRequest, context) === true) {
          allowedCollections.push(collection);
        }
      });

      response.data.body.collections[collectionType] = allowedCollections;

      return response;
    };

    if (['all', 'stored', 'realtime'].indexOf(type) === -1) {
      return q.reject(new BadRequestError('listCollections: unrecognized type argument: "' + type + '"'));
    }

    kuzzle.pluginsManager.trigger('data:listCollections', requestObject);

    if (type === 'stored') {
      return kuzzle.services.list.readEngine.listCollections(requestObject).then(response => {
        response.data.body.type = type;
        return q(filterCollections(response, 'stored'));
      });
    }

    realtimeCollections = kuzzle.hotelClerk.getRealtimeCollections();

    if (type === 'realtime') {
      return q(filterCollections(new ResponseObject(requestObject, {type, collections: {realtime: realtimeCollections}}), 'realtime'));
    }

    return kuzzle.services.list.readEngine.listCollections(requestObject)
      .then(response => {
        response.data.body.type = type;
        response.data.body.collections.realtime = realtimeCollections;
        filterCollections(response, 'realtime');
        filterCollections(response, 'stored');
        return q(response);
      });
  };

  this.now = function (requestObject) {
    kuzzle.pluginsManager.trigger('data:now', requestObject);

    return q(new ResponseObject(requestObject, {now: Date.now()}));
  };

  this.listIndexes = function (requestObject, context) {
    kuzzle.pluginsManager.trigger('data:listIndexes', requestObject);

    return kuzzle.services.list.readEngine.listIndexes(requestObject)
      .then(response => {
        var
          availableIndexes = response.data.body.indexes,
          userRoles = context.token.user.profile.roles,
          allowedIndexes = [];

        if (response.data.body.indexes.length > 0) {
          userRoles.forEach(role => {
            if (role.indexes !== undefined) {
              _.forEach(role.indexes, (value, roleIndex) => {
                if (roleIndex.charAt(0) !== '_') {
                  availableIndexes.forEach(availableIndex => {
                    if ((availableIndex === roleIndex ||
                      roleIndex === '*' && availableIndex !== internalIndex) &&
                      _.indexOf(allowedIndexes, availableIndex) === -1
                    ) {
                      allowedIndexes.push(availableIndex);
                    }
                  });
                }
              });
            }
            response.data.body.indexes = allowedIndexes;
          });
        }

        return response;
      });
  };

  this.serverInfo = function (requestObject) {
    var
      serviceName,
      response = {
        kuzzle: {
          version: kuzzle.config.version,
          api: {
            version: kuzzle.config.apiVersion,
            routes: {}
          },
          nodeVersion: process.version,
          memoryUsed: process.memoryUsage().rss,
          uptime: process.uptime() + 's',
          plugins: {},
          system: {
            memory: {
              total: os.totalmem(),
              free: os.freemem()
            },
            cpus: os.cpus()
          }
        },
        services: {}
      };

    Object.keys(kuzzle.funnel).forEach(controller => {
      var actionList = [];

      if (typeof kuzzle.funnel[controller] === 'object') {
        Object.keys(kuzzle.funnel[controller]).forEach(action => {
          if (typeof kuzzle.funnel[controller][action] === 'function') {
            actionList.push(action);
          }
        });

        if (actionList.length > 0) {
          response.kuzzle.api.routes[controller] = actionList;
        }
      }
    });

    Object.keys(kuzzle.pluginsManager.plugins).forEach(plugin => {
      var
        pluginInfo = kuzzle.pluginsManager.plugins[plugin],
        p = {
          name: pluginInfo.name,
          version: pluginInfo.version,
          activated: pluginInfo.activated
        };

      p.hooks = _.uniq(Object.keys(pluginInfo.object.hooks));

      response.kuzzle.plugins[plugin] = p;
    });

    return Object.keys(kuzzle.services.list).reduce((previous, current) => {
      return previous.then(serviceInfo => {
        if (serviceInfo) {
          response.services[serviceName] = serviceInfo;
        }

        serviceName = current;

        if (kuzzle.services.list[current].getInfos) {
          return kuzzle.services.list[current].getInfos();
        }

        return q();
      });
    }, q())
    .then(serviceInfo => {
      if (serviceInfo) {
        response.services[serviceName] = serviceInfo;
      }

      return new ResponseObject(requestObject, {serverInfo: response});
    });
  };
};
@@ -873,37 +873,28 @@
 equestObject
-, context
 ) %7B%0A
+
     var%0A    
@@ -973,636 +973,8 @@
 s;%0A%0A
-    var filterCollections = (response, collectionType) =%3E %7B%0A      var rightsRequest = %7B%0A          action: 'listCollections',%0A          controller: 'read',%0A          index: requestObject.index%0A        %7D,%0A        allowedCollections = %5B%5D;%0A%0A      response.data.body.collections%5BcollectionType%5D.forEach(collection =%3E %7B%0A        rightsRequest.collection = collection;%0A%0A        if (context.token.user.profile.isActionAllowed(rightsRequest, context) === true) %7B%0A          allowedCollections.push(collection);%0A        %7D%0A      %7D);%0A%0A      response.data.body.collections%5BcollectionType%5D = allowedCollections;%0A%0A      return response;%0A    %7D;%0A%0A
     
@@ -1405,45 +1405,16 @@
 n q(
-filterCollections(response, 'stored')
+response
 );%0A 
@@ -1546,34 +1546,16 @@
 eturn q(
-filterCollections(
 new Resp
@@ -1633,29 +1633,16 @@
 tions%7D%7D)
-, 'realtime')
 );%0A    %7D
@@ -1775,32 +1775,32 @@
 dy.type = type;%0A
+
         response
@@ -1858,104 +1858,8 @@
 ns;%0A
-        filterCollections(response, 'realtime');%0A        filterCollections(response, 'stored');%0A
     

Remove filter collection on listCollection once it is allowed in funnel