'use strict';

var angular = require('angular');
require('./modules');
require('./services/VPNManagerService');
require('../appInitFlow/services/appInitFlow');
require('./services/vpnService');

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

module.config(function($httpProvider) {
  $httpProvider.interceptors.push('waitLoginVPNHttpRequestInterceptor');
});

module.factory('waitLoginVPNHttpRequestInterceptor', function($injector) {
  function waitLoginVPN(config) {
      var applicationConfig = $injector.get('CoreAppConfig').applicationConfig;
      if (applicationConfig.getKeyValue('vpnServer')) {
          return $injector.get('vpnService').waitLoginVpn()
            .then(function() {return config;});
      } else {
          return config;
      }
  }

  return {
    request: function(config) {
      if (config.url.indexOf('views') === -1) {
        var applicationConfig = $injector.get('CoreAppConfig').applicationConfig;
        if (!applicationConfig.getServerUrl()) {
          return applicationConfig.getKeyValueUntilNoEmpty('serverUrl')
          .then(function() {
            return waitLoginVPN(config);
          });
        } else {
            return waitLoginVPN(config);
        }
      }
      return config;
    }
  };
});

module.exports = module;
