'use strict';

var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');
require('./NoticeRemoteService');
require('./NoticeCache');
require('./AppNotices');

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

module.factory('NoticeService', NoticeService);

/**
 * @ngInject
 *
 * 通知的统筹管理
 */
function NoticeService(AppNotices, NoticeCache, LinkerService, NoticeRemoteService,
  AppConfig, $rootScope, $timeout) {

  var appNotices  = new AppNotices();

  var service = {
    appNotices: appNotices,
    refresh: refresh,
    insert: insert, //用于测试
    clear: clear,
    changeUser: changeUser,
    updateUserIds: updateUserIds,
    loadFromCache: loadFromCache //用于测试
  };

  $rootScope.$on('websocket.notice', function(event, message) {
    var _notices = (message) ? message.data : [];
    service.insert(_notices);
  });

  function refresh() {
    var userId = LinkerService.currentUserId;
    if (userId) {
      service.loadFromCache(userId);
      return getFromRemote().then(insert);
    }
  }

  function loadFromCache(userId) {
    var notices = NoticeCache.getNotices(userId);
    appNotices.push(notices);
  }

  function getFromRemote() {
    var version = appNotices.getMaxVersion();
    return NoticeRemoteService.getNotice(version);
  }

  function insert(notices) {
    var userId = LinkerService.currentUserId;
    appNotices.push(notices);
    service.updateUserIds(userId);
    NoticeCache.updateNotices(userId, appNotices.notices);
  }

  function clear() {
    appNotices.clear();
    NoticeCache.clearNotices();
    NoticeCache.clearUserIds();
  }

  function changeUser() {
    appNotices.clear();
  }

  function updateUserIds(userId) {
    NoticeCache.updateUserIdsHistory(userId);
  }

  return service;
}
