var angular = require('angular');
require('../modules');
require('../services/CurrentTaskService');
'use strict';

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

module.directive('taskPushedMessage', function($rootScope, $timeout, $state,
	$ionicScrollDelegate, CurrentTaskService) {

	return {
		restrict: 'AE',
		replace: true,
		templateUrl: 'views/task/directives/taskpushedmessage.tpl.html',
		link: function(scope, element) {
			/**
			 * 推送聊天消息。
			 * @param  {Task} task 需要推送的聊天消息的所属任务
			 */
			function pushMessage(task) {
				scope.pushedTask = task;
				scope.pushedMessage = task.latestMessage;
				scope.changed = true;
				$timeout(function() {
					scope.changed = false;
				}, 6000);
			}
			/**
			 * 追加聊天消息。
			 * 1.修改当前任务的最新聊天消息
			 * 2.向discussions中添加一个聊天信息
			 * 3.修改缓存中的任务
			 * @param  {Task} task 需要追加的聊天消息的所属任务
			 */
			function appendMessage(event, task) {
				var currentScopeTask = event.currentScope.task;
				currentScopeTask.latestMessage = task.latestMessage;
				currentScopeTask.discussions.push(task.latestMessage);
				$rootScope.$broadcast('task.update', currentScopeTask);
				$rootScope.$broadcast('task.noticeNum.reset', currentScopeTask.id);
				$timeout(function() {
					$ionicScrollDelegate.$getByHandle('mainScroll').scrollBottom();
				});
			}

			scope.$on('push.taskmessage', function(event, task) {
				if(task.id === event.currentScope.task.id) {
					appendMessage(event, task);
				}else {
					pushMessage(task);
				}
			});

			scope.close = function() {
				element.remove();
			};

			scope.goToDetail = function() {
				CurrentTaskService.changeCurrentTask(scope.pushedTask).then(function() {
					$state.go('mission.taskDiscuss', {
						taskId: scope.pushedTask.id
					});
				});

			};
		}
	};
});