var angular = require('angular');
require('../modules');
var module = angular.module('commons.directives');
var enter = true;

module.run(function($rootScope) {
  $rootScope.$on('$ionicView.beforeEnter', function() {
    enter = false;
  });

  $rootScope.$on('$ionicView.enter', function() {
    enter = true;
  });
});

module.directive('sinoLoadingHint', function($rootScope, $timeout) {
  var defaultConfig = {
    loadingTitle: '载入中...',
    errorTitle: '数据加载失败！',
    nodataTitle: '无数据'
  };

  function getHintConfig($attr) {
    var config = {};
    for (var key in defaultConfig) {
      if (defaultConfig.hasOwnProperty(key)) {
        config[key] = $attr[key] || defaultConfig[key];
      }
    }

    return config;
  }

  return {
    restrict: 'E',
    templateUrl: 'views/commons/directives/sinoLoadingHint.tpl.html',
    replace: true,
    transclude: true,
    scope: {
      state: '=',
      refresh: '&'
    },
    link: function(scope, element, $attr) {
      scope.state = scope.state || 1;
      if (scope.state == 2) {
        scope.showContent = true;
        $timeout(function() {
          $rootScope.$broadcast('$sino-loading-hint-show-content');
        }, 100);
      }
      scope.config = getHintConfig($attr);
      scope.needRefresh = !!$attr.refresh;
      scope.$watch(function() {
        if (scope.state == 3) {
          scope.showContent = false;
        }
      });
      scope.$watch(function() {
        return scope.state == 2 && enter;
      }, function(show) {
        if (!scope.showContent) {
          scope.showContent = show;
          $timeout(function() {
            $rootScope.$broadcast('$sino-loading-hint-show-content');
          }, 100);
        };
      });

    }
  };
});
