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

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

function transformFormData(data) {
  return encodeURIComponent(data);
}
function transformRequest(data) {
  var items = [];
  if(_.isObject(data)) {
    for(var key in data) {
      if(data.hasOwnProperty(key) && !_.isEmpty(data[key])) {
        if(_.isObject(data[key])) {
          for(var keyInDataKey in data[key]) {
            if(data[key].hasOwnProperty(keyInDataKey)) {
              items.push(key + '.' + keyInDataKey + '=' + transformFormData(data[key][keyInDataKey]));
            }
          }
        } else {
          items.push(key + '=' + transformFormData(data[key]));
        }
      }
    }
  }

  return items.join('&');
}

/**
 * @ngdoc service
 * @name commons.formDataRequestInterceptor
 * @description 表单请求数据处理器
 * @return {[type]} [description]
 */
module.factory('formDataRequestInterceptor', function($rootScope) {
  return {
    request: function(config) {
      if (config.headers && config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
        config.transformRequest = transformRequest;
      }
      return config;
    },
    response: function(response) {
      return response;
    }
  };
});

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