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

module
  .factory('PersonImgCache', PersonImgCache)
  .factory('PersonImgFileCache', PersonImgFileCache)
  .factory('PersonImgRemoteService', PersonImgRemoteService);

/** @ngInject */
function PersonImgCache(PersonImgFileCache, PersonImgRemoteService) {
  var validityCache = {};//有效期缓存
  var remoteService = PersonImgRemoteService;
  var imgFileCache = PersonImgFileCache;
  var watcherMap = {};

  var imgCache = {
    getPersonImgUrl: getPersonImgUrl,
    syncPersonImgUrl: syncPersonImgUrl,
    listen: listen,
    trigger: trigger,
    fileCache: fileCache, //为了测试
    DateCache: validityCache //为了测试
  };

  return imgCache;

  function fileCache(userId) {
    return imgFileCache.getImgCacheByUserId(userId);
  }

  function getPersonImgUrl(userId) {
    var nowTime = Date.now();
    if(!_.isEmpty(validityCache[userId]) && validityCache[userId] > nowTime) { // 30分钟有效期内
      return imgCache.fileCache(userId);
    } else {
      imgCache.syncPersonImgUrl(userId);
      return imgCache.fileCache(userId);
    }
  }

  function syncPersonImgUrl(userId) {
    var promise = remoteService.getImgUrlByUserId(userId);
    return promise.then(function(data) { // 获取成功
      validityCache[userId] = Date.now() + 30 * 60 * 1000;//获取成功，不管有没有url，都保存个时间。
      var personImgUrl = data.url;
      if(personImgUrl && personImgUrl !== imgCache.fileCache(userId)) {// 更新图片链接
        imgFileCache.addOrUpdate(userId, personImgUrl);
      } else if(!personImgUrl) { // 没有值，则删去原来缓存中的值
        imgFileCache.deleteByUserId(userId);
      }
      return personImgUrl;
    }).then(function(personImgUrl) {
      imgCache.trigger(userId, personImgUrl);// 发布
    });
  }

  function listen(name, callFn) {
    var watchers = watcherMap[name] || [];
    watchers.push(callFn);
    watcherMap[name] = watchers;
  }

  function trigger(name) {
    var watchers = watcherMap[name];
    var params = [];
    for (var i = 1; i < arguments.length; i++) {
      params.push(arguments[i]);
    }
    if (watchers) {
      _.each(watchers, function(watcher) {
        watcher.apply(null, params)
      });
    }
  }
}

/** @ngInject */
function PersonImgFileCache() {
  var imgCache;

  var service = {
    getImgCache: getImgCache,
    setImgCache: setImgCache,
    addOrUpdate: addOrUpdate,
    deleteByUserId: deleteByUserId,
    getImgCacheByUserId: getImgCacheByUserId
  };

  return service;
  function getImgCache() {
    if (!imgCache) {
      imgCache = JSON.parse(localStorage.getItem('_person_img_url'));
    }
    return imgCache;
  }

  function setImgCache(map) {
    var jsonMap = JSON.stringify(map);
    localStorage.setItem('_person_img_url', jsonMap);
  }

  function addOrUpdate(userId, url) {
    var imgCache = this.getImgCache() || {};
    imgCache[userId] = url;
    this.setImgCache(imgCache);
  }

  function deleteByUserId(userId) {
    var imgCache = this.getImgCache() || {};
    if(imgCache.hasOwnProperty(userId)) {
      delete(imgCache[userId]);
    }
    this.setImgCache(imgCache);
  }

  function getImgCacheByUserId(userId) {
    var imgCache = this.getImgCache();
    return imgCache ? imgCache[userId] : null;
  }
}
/** @ngInject */
function PersonImgRemoteService($http) {
  var userPhotoUrlPromiseCache= {};
  return{
    getImgUrlByUserId: getImgUrl
  };

  function getImgUrl(userId) {
    if(userPhotoUrlPromiseCache[userId]) {
      return userPhotoUrlPromiseCache[userId];
    } else {
      var promise = getImgUrlByUserId(userId);
      userPhotoUrlPromiseCache[userId] = promise;
      return promise;
    }
  }
  /**
   * 从远端获取，该用户是否有头像图片
   * 有：返回的是fileId
   * 无：返回的是‘’
   */
  function getImgUrlByUserId(userId) {
    return $http.get('/base-user/user/url/' + userId + '/photo', {
      timeout: 15000
    }).then(function(response) {
      return response.data;
    })['finally'](function() {
      delete userPhotoUrlPromiseCache[userId];
    });
  }
}
