var angular = require('angular');
require('../modules');
require('../services/AppConnected');

var module = angular.module('commons.directives.sinoConnected');

module.directive('sinoConnected', function($rootScope, $timeout, AppConnected) {

  return {
    restrict: 'EA',
    scope: {
    },
    replace: true,
    templateUrl: 'views/commons/directives/sinoConnected.tpl.html',
    link: function(scope) {
      scope.loaded = false;

      function applyNetStatus(netStatus) {
        if(netStatus) {
          scope.connected = netStatus.connected;
          scope.netStatus = netStatus;
          scope.loaded = true;
        } else {
          scope.connected = false;
          scope.netStatus = {networkConnected: false};
        }
      }

      scope.$on('server.online', function(event, netStatus) {
        scope.connected = true;
        scope.netStatus = netStatus;
      });

      scope.$on('server.offline', function(event, netStatus) {
        scope.connected = false;
        scope.netStatus = netStatus;
      });

      scope.setConnectedInfo = function() {
        AppConnected.getConnected().then(applyNetStatus);
      };

      $timeout(function() {
        scope.setConnectedInfo();
      }, 500);
    }
  };
});
