var angular = require('angular');
require('../modules');
require('../../../commons/services/PageableCacheArray');
require('./LinkerCache');
require('./LinkerService');

var module = angular.module('linker.services');

module.factory('userListOfSameDept', function(
  PageableCacheArray,
  $rootScope,
  LinkerCache,
  LinkerService) {

  var isSameDept = function(currentUser, user) {
    if (!currentUser) { return; }
    var currentDeptIds = (currentUser.deptId || '').split(','),
      deptIds = (user.deptId || '').split(',');

    for (var i = 0, len = currentDeptIds.length; i < len; i++) {
      if (deptIds.indexOf(currentDeptIds[i]) >= 0) {
        return true;
      }
    }

    return false;
  };

  var userListOfSameDept = new PageableCacheArray('linker.userList', 100000);
  /**
   * @override
   */
  userListOfSameDept.loadAllItems = function() {
    var self = this;
    self.allItems = [];
    return LinkerService.getCurrentUser().then(function(currentUser) {
      return LinkerCache.get(self.ids).then(function(users) {
        self.allItems = _.filter(users, function(user) {
          return isSameDept(currentUser, user);
        });
        return self.allItems;
      });
    });
  };

  $rootScope.userListOfSameDept = userListOfSameDept;
  return userListOfSameDept;
});
