var angular = require('angular');
require('../modules');
require('./TaskCacheArray');
require('./TaskRemoteService');
require('./TaskRepository');

'use strict';

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

module.factory('taskMessages', function($rootScope, TaskCacheArray, TaskRemoteService, TaskRepository, $q) {

  var messageCacheArray = new TaskCacheArray('task.message', 20);
  messageCacheArray.scrollPosition = {left: 0, top: 0};

  messageCacheArray.queryList = function(pageNo) {
    var self = this;
    return TaskRemoteService.queryMessageList(pageNo).then(function(data) {
      self.number = data.number;
      self.totalPages = data.totalPages;
      if(data.content.length > 0) {
        $rootScope.$broadcast('dispatchnotice.add', self.wrapMessage(data.content[0]));
      }
      return TaskRepository.addOrUpdateTasks(self.transferMessages(data).content);
    }, function() {
      self.totalPages = -1;
      return $q.when();
    });
  };

  messageCacheArray.wrapMessage = function(message) {
    return {
      type: 'DispatchNotice',
      data: message
    };
  };

  /**
   * 将消息数据列表转化成以任务为单位的数据。
   * @param  {Object} data 消息列表数据，含数据分页信息
   */
  messageCacheArray.transferMessages = function(data) {
    data.content = jsUtil.map(data.content, function(item) {
      var newData = {};
      jsUtil.apply(newData, item.recordObject);
      newData.latestMessage = item;
      return newData;
    });
    return data;
  };
  
  return messageCacheArray;
});