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

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

module.factory('App', function($http, AppConfig, $rootScope, $timeout) {

  var App = {
    config: AppConfig,

    setNetworkState: function(state) {
      if (App.online !== state) {
        App.online = state;
        $rootScope.$evalAsync(function() {
          App.online = state;
        });
      }
    },

    ping: function() {
      if (this.pingPromise) {
        return this.pingPromise;
      }
      this.pingPromise = $http({
        url: '/base-user/loginUser',
        method: 'OPTIONS',
        timeout: 450
      }).then(function() {
        delete App.pingPromise;
        App.setNetworkState(true);
      }, function(error) {
        delete App.pingPromise;
        if (error && error.status === 0) {
          App.setNetworkState(false);
        } else {
          App.setNetworkState(true);
        }
      });
      return this.pingPromise;
    },

    beginMonitor: function() {
      function ping() {
        App.ping().then(function() {
          if (App.online === false) {
            $timeout(function() {
              ping();
            }, 500);
          }
        });
      }

      window.addEventListener('online', function() {
        ping();
      });

      window.addEventListener('offline', function() {
        App.setNetworkState(false);
      });

      if (window.navigator.onLine) {
        ping();
      }
    }
  };
  return App;
});
