var angular = require('angular'),
  _ = require('jsUtil');

require('../modules');
require('../../../commons/services/CacheService');
require('./FavoriteLinker');
require('./LinkerService');
require('./LinkerRemoteService');
require('./FavoriteLinkerCache');
require('./LinkerCache');

angular
  .module('linker.services')
  .factory('FavoriteLinkerService', FavoriteLinkerService);

/** @ngInject */
function FavoriteLinkerService($q, $rootScope, FavoriteLinker, CacheService,
  LinkerService, LinkerRemoteService, FavoriteLinkerCache, LinkerCache, ConfigApp) {
  var refreshed = false,
    addFavoritePromises = {}, //暂存一下已经添加进常用联系人的userIds
    removeFavoritePromise = {};//暂存一下已经删除进常用联系人的userIds

  var favoriteLinker = new FavoriteLinker();
  return {
    favoriteLinker: favoriteLinker,
    sync: sync,
    refresh: refresh,
    add: add,
    remove: remove,
    clear: clear,
    isFavorite: isFavorite,
    _filterUsers: filterUsers,
    _syncCache: syncCache, //用于测试
    _syncRemote: syncRemote, //用于测试
    _refreshCache: refreshCache,
    _refreshRemote: refreshRemote
  };

  /**
   * 1. 初始化从缓存中获取常用联系人
   * 2. 从远端去更新常用联系人
   */
  function sync() {
    if(!ConfigApp.allUersGetMethod) {
      return this._syncCache();
    } else {
      return this._syncRemote();
    }
  }

  function syncCache() {
    var userId = LinkerService.currentUserId,
      favoriteUserIds = FavoriteLinkerCache.get(userId);
    return LinkerCache.get(favoriteUserIds).then(function(users) {
      favoriteLinker.add(users);
      FavoriteLinkerCache.update(userId, favoriteLinker.getUserIds());
      return users;
    }).then(function() {
      refreshCache();
    });
  }

  function syncRemote() {
    var userId = LinkerService.currentUserId;
    return LinkerRemoteService.queryFavoriteUsers(userId)
    .then(function(users) {//从远端获取到的userIds
      favoriteLinker.add(filterUsers(users));
      FavoriteLinkerCache.update(userId, favoriteLinker.getUserIds());
      return users;
    });
  }

  /**
   * 获取最新的常用联系人
   */
  function refresh(force) {
    if (refreshed && force !== true) {
      return $q.when(null);
    }
    if(!ConfigApp.allUersGetMethod) {
      return this._refreshCache(force);
    } else {
      return this._refreshRemote(force);
    }
  }

  function refreshRemote(force) {
    refreshed = true;
    return this._syncRemote();
  }

  function refreshCache(force) {
    refreshed = true;
    var userId = LinkerService.currentUserId;

    return LinkerRemoteService.queryFavorite(userId)
    .then(function(linkermansIds) {//从远端获取到的userIds
      FavoriteLinkerCache.update(userId, linkermansIds);
      return LinkerCache.get(linkermansIds);
    }).then(function(users) {//从LinkerCache中获取的users
      return LinkerCache.updateUser(users);//更新用户缓存
    }).then(function(users) {
      favoriteLinker.add(filterUsers(users));
      return users;
    });
  }

  /**
   * 添加常用联系人
   * @param {[String]} linkermanUserIds
   */
  function add(linkermanUserIds, users) {
    var userId = LinkerService.currentUserId;
    linkermanUserIds = _.filter(linkermanUserIds, function(userId) {
      return !addFavoritePromises[userId];
    });
    if(linkermanUserIds.length === 0) {
      return;
    }

    return LinkerRemoteService.favoriteUserById(userId, linkermanUserIds)
    .then(function() {
      if(users) {
        return $q.when(users);
      }
      return LinkerCache.get(linkermanUserIds);
    }).then(function(users) {
      favoriteLinker.add(filterUsers(users));//favoriteLinker添加进去之后
      FavoriteLinkerCache.update(userId, favoriteLinker.getUserIds());
    }).then(function() {//更新addFavoritePromises 并发布favoriteUpdate事件
      linkermanUserIds.forEach(function(linkermanUserId) {
        delete addFavoritePromises[linkermanUserId];
      });
      $rootScope.$broadcast('favoriteUpdate');
    });

    linkermanUserIds.forEach(function(linkermanUserId) {
      addFavoritePromises[linkermanUserId] = true;
    });
  }

  /**
   * 删除常用联系人
   * @param  {[String]} linkerUserId
   */
  function remove(linkerUserId) {
    var userId = LinkerService.currentUserId;
    if (!removeFavoritePromise[linkerUserId]) {
      return LinkerRemoteService.deleteFavoriteById(userId, linkerUserId)
      .then(function() {
        favoriteLinker.remove(linkerUserId);
        FavoriteLinkerCache.update(userId, favoriteLinker.getUserIds());
        return userId;
      }).then(function() {
        delete removeFavoritePromise[linkerUserId];
        $rootScope.$broadcast('favoriteUpdate');
      });
      removeFavoritePromise[linkerUserId] = true;
    }
  }

  /**
   * 判断是否在常用联系人中
   * @param  {[String]}  userId
   * @return {Boolean}
   */
  function isFavorite(userId) {
    return favoriteLinker.isFavorite(userId);
  }

  /**
   * 清空联系人
   */
  function clear() {
    favoriteLinker.clear();
  }

  /**
   * 过滤虚拟用户
   */
  function filterUsers(users) {
    var _users = [];
    _.each(users, function(user) {
      if(user.note === '1') {//真实用户
        _users.push(user);
      }
    });
    return _users;
  }
}
