var angular = require('angular');
require('jsUtil');
require('../modules');
require('../../notice/services/NoticeService');
'use strict';

var module = angular.module('find');

module.controller('FindCtrl', function($scope, AppConfig, $state, $q, NoticeService, $rootScope) {
  $scope.modules = AppConfig.modules;

  $scope.loading = {};

  $scope.$on('$ionicView.beforeEnter', function() {
    AppConfig.refreshModulesAuth();
    refresh();
    refreshNoticeUnreadNum();
  });

  function refresh() {
    NoticeService.refresh();
  }

  function refreshNoticeUnreadNum() {
    var notices = NoticeService.appNotices.notices;
    var num = 0;
    if(notices) {
      _.each(notices, function(item) {
        if(AppConfig.showInNotice(item.moduleName)) {
          num = num + item.unreadNum;
        }
      });
    }
    NoticeService.appNotices.unreadNum = num;
    $rootScope.appNotices = NoticeService.appNotices;
  }

  $scope.getUnreadNum = function(module) {
    var unreadNum = 0;
    _.each(NoticeService.appNotices.notices, function(notice) {
      if(notice.moduleName === module.moduleName) {
        unreadNum = notice.unreadNum;
      }
    });
    return unreadNum;
  };

  $scope.toModule = function(module) {
    if (module._level_top && module._children.length > 0) {
      if (module._open) {
        module.close();
      } else {
        module.open();
      }
      return;
    }

    if (!module && $scope.loading[module.moduleName]) { return; }

    if (module.state instanceof Function) {
      $scope.loading[module.moduleName] = true;
      var result = module.state();
      $q.when(result).then(function() {
        $scope.loading[module.moduleName] = false;
      });
    } else {
      $state.go(module.state);
    }
  };
});
