var angular = require('angular');
require('uiRouter');
require('../modules');
require('../../login/services/LoginService');
'use strict';

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

module.run(function($rootScope, $state) {
  $rootScope.$on('socket.push.taskmessage', function(event, socketEvent) {
    var message = JSON.parse(socketEvent.data);
    var newData = {};
    jsUtil.apply(newData, message.recordObject);
    newData.latestMessage = message;
    $rootScope.$broadcast('task.update', newData);

    if ($state.current.name === 'mission.taskDiscuss') {
      $rootScope.$broadcast('message.pushed', newData);
    }
  });
});

module.factory('TaskDiscussService', function($http, $rootScope) {
  var service = {
    /**
     * 添加任务讨论。
     */
    addDiscuss: function(discuss) {
      return $http.post('/discuss', discuss).then(function(response) {
        return response.data;
      });
    },

    loadDiscussions: function(taskId) {
      return $http.get('/discuss?recordId=' + taskId).then(function(response) {
        $rootScope.$broadcast('task.noticeNum.reset', taskId);
        return response.data;
      });
    }
  };

  return service;
});