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

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

module.config(function($httpProvider) {
  $httpProvider.interceptors.push('httpRequestInterceptor');
  $httpProvider.interceptors.push('httpResponseInterceptor');
  $httpProvider.interceptors.push('httpResponseErrorInterceptor');
});

module.factory('httpResponseInterceptor', function($q, $location, $rootScope) {
  return {
    response: function(response) {
      var deferred = $q.defer();
      if (!response) {
        deferred.reject(response);
      } else if (response.status === 403 && response.data && response.data.message === '凭证过期') {
        $rootScope.storedUrl = $location.url();
        $rootScope.$broadcast('certificateExpires');
        return $q.reject(response);
      } else {
        deferred.resolve(response);
      }
      return deferred.promise;
    }
  };
});

module.factory('httpRequestInterceptor', function($injector, $window) {
  return {
    request: function(config) {
      if (config.url.indexOf('views') === -1) {
        var applicationConfig = $injector.get('CoreAppConfig').applicationConfig;
        if (!config.noContainUserToken) {
          config.headers.userToken = localStorage.getItem('userToken') ? localStorage.getItem('userToken') : '';
        }
        config.withCredentials = true;
        
        if (!applicationConfig.getServerUrl()) {
          return applicationConfig.getKeyValueUntilNoEmpty('serverUrl')
          .then(function(serverUrl) {
            config.url = serverUrl + config.url;
            return config;
          });
        } else {
          config.url = applicationConfig.getServerUrl() + config.url;
        }
      }
      return config;
    }
  };
});

module.factory('httpResponseErrorInterceptor', function($q, $rootScope, $location) {
  return {
    responseError: function(response) {
      if ((response.status === 403 && response.data && response.data.message === '凭证过期') ||
          (response.status === 401 && response.data && response.data.message === '尚未登录')) {
        $rootScope.storedUrl = $location.url();
        $rootScope.$broadcast('certificateExpires');
        return $q.reject(response);
      }
      $rootScope.$broadcast('responseError', '请求失败，请检查网络连接。');
      return $q.reject(response);
    }
  };
});
