/** 处理connected状态 */


var angular = require('angular');
require('../modules');
require('./configService');

var module = angular.module('commons.services.connected');

module.run(function($rootScope, AppConnected) {

  document.addEventListener('server.online', function(event) {
    $rootScope.$evalAsync(function() {
      $rootScope.$broadcast('server.online', event.netStatus);
    });
  }, false);

  document.addEventListener('server.offline', function(event) {
    $rootScope.$evalAsync(function() {
      $rootScope.$broadcast('server.offline', event.netStatus);
    });
  }, false);
  
  $rootScope.$on('server.online', function() {
    $rootScope.connected = true;
  });

  $rootScope.$on('server.offline', function() {
    $rootScope.connected = false;
  });
  
  AppConnected.getConnected();
});

module.factory('AppConnected', function($q, $rootScope, configService) {

  function getConnected() {
    var deferred = $q.defer();
    if (window.SinoNetwork) {
      window.SinoNetwork.netstatus(function (netStatus) {
        $rootScope.netWorkStatus = netStatus.connected?'online' : 'offline';
        $rootScope.connected = netStatus.connected;
        $rootScope.netWorkStatus = netStatus.connected?'online' : 'offline';
        deferred.resolve(netStatus);
      }, deferred.reject);
    } else {
      $rootScope.connected = true;
      deferred.resolve({
        connected: true,
        networkConnected: true,
        wifiConnected: false,
        mobileConnected: false
      });
      $rootScope.$broadcast('server.online');
    }
    return deferred.promise;
  }

  var services = {
    getConnected: getConnected
  };

  return services;
});
