'use strict';

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

angular
  .module('notice')
  .run(noticeRun)
  .directive('sinoNgInit', sinoNgInit)
  .directive('sinoNoticeTitle', sinoNoticeTitle)
  .directive('sinoNoticeSendTime', sinoNoticeSendTime)
  .controller('NoticeListCtrl', NoticeListCtrl);

/** @ngInject */
function NoticeListCtrl($scope, $timeout,
  $state, $ionicScrollDelegate, CommonService, NoticeService,
  userList, AppConfig, introService) {

  $scope.isRefresh = false; // 记录是否刷新过，为了防止无通知闪屏
  $scope.appNotices = NoticeService.appNotices;
  $scope.onRefresh = onRefresh;
  $scope.networkTitle = '当前网络不可用，请检查你的网络设置。';

  init();

  function init() {
    $scope.$on('$ionicView.beforeEnter', function() {
      $scope.onRefresh();
    });

    /**
    * scope作用域销毁时将搜索弹层移除。
    */
    $scope.$on('$destroy', function() {
      if ($scope.chooseTalkerModal) {
        $scope.chooseTalkerModal.remove();
      }
    });
  }

  function onRefresh() {
    return NoticeService.refresh().then(function() {
      $scope.isRefresh = true;
    }).finally(function() {
      $scope.$broadcast('scroll.refreshComplete');
    });
  };
}

/** @ngInject */
function noticeRun($rootScope, NoticeService, AppConfig) {
  // 初始化rootScope中的notices
  var $scope = $rootScope.$new();
  $scope.appNotices1 = NoticeService.appNotices;

  $scope.$watch('appNotices1.notices', function(notices) {
    var num = 0;
    if(!notices) return;
    _.each(notices, function(item) {
      if(AppConfig.showInNotice(item.moduleName)) {
        num = num + item.unreadNum;
      }
    });
    NoticeService.appNotices.unreadNum = num;
    $rootScope.appNotices = NoticeService.appNotices;
  }, true);
};

/** @ngInject */
function sinoNgInit($timeout) {
  return {
    restrict: 'C',
    compile: function compile() {
      return {
        post: function postLink(scope, iElement) {
          $timeout(function() {
            iElement[0].classList.remove('sino-ng-init');
          }, 100);
        }
      };
    }
  };
}

/** @ngInject */
function sinoNoticeTitle($rootScope) {
  return {
    restrict: 'E',
    templateUrl: 'views/notice/sinoNoticeTitle.tpl.html',
    replace: true,
    scope: true,
    link: function(scope) {
      scope.inTryConnecting = false;
      scope.$watch(function() {
        scope.inTryConnecting = $rootScope.inTryConnecting;
        return scope.inTryConnecting;
      });
    }
  };
}

/** @ngInject */
function sinoNoticeSendTime() {
  return {
    restrict: 'E',
    template: '<span class="item-note" style="margin-left: 20px;"></span>',
    replace: true,
    link: function(scope, element, attrs) {

      attrs.$observe('sendTime', function(sendTime) {
        if(sendTime) {
          var date = _.parseDate(sendTime, 'Y-m-dTH:i:s.uZ');
          element.text(_.smartListDateParser(date));
        }
      });
    }
  }
}
