var angular = require('angular'),
  _ = require('jsUtil');
require('./modules');
require('../../commons/services/localforage');
var module = angular.module('linker');

module.run(function(userDeptList, userListOfSameDept, $rootScope) {
  var clearPromise = null;
  $rootScope.$on('serverUrl.changed', function() {
    clearPromise = userDeptList.clear();
  });

  $rootScope.$on('server.online', function() {
    if (clearPromise) {
      clearPromise.then(function() {
        userDeptList.sync().then(function() {
          return userListOfSameDept.loadFromCache();
        });
      });
    } else {
      userDeptList.sync().then(function() {
        return userListOfSameDept.loadFromCache();
      });
    }
  });

  $rootScope.$on('login', function() {
    userListOfSameDept.loadFromCache();
  });
});

module.run(function($rootScope, FavoriteLinkerService) {
  var loadFromCache = false;
  $rootScope.$on('loginNewUser', function() {
    FavoriteLinkerService.clear();
    FavoriteLinkerService.refresh(true);
  });

  $rootScope.$on('serverUrl.changed', function() {
    FavoriteLinkerService.clear();
  });
});

module.run(function(FavoriteLinkerCache, localforage, LinkerService,  $timeout) {
  $timeout(function() {
    var userId = LinkerService.currentUserId;
    if (!userId) {
      return userId;
    }
    var _update = window.localStorage['#linkercachesync'];

    if(_.isEmpty(_update)) {//一次性的从localForage中将缓存取出并放入localStorage
      localforage.getItem('linker.linkerList')
      .then(function(linkermansIds) {
        FavoriteLinkerCache.update(userId, linkermansIds);
        localforage.removeItem('linker.linkerList');
        window.localStorage['#linkercachesync'] = true;
      });
    }
  }, 300);

});
