'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CALL_API = undefined;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /*eslint no-unused-vars: 1*/
/*global __SERVER__ */

var _config = require('../../server/config');

var _config2 = _interopRequireDefault(_config);

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _superagent = require('superagent');

var _superagent2 = _interopRequireDefault(_superagent);

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var CALL_API = exports.CALL_API = Symbol('CALL_API');

function formatUrl(path) {
  if (__SERVER__) {
    // Prepend host and port of the API server to the path.
    return 'http://' + _config2.default.apiHost + ':' + _config2.default.apiPort + path;
  }
  // Prepend `/api` to relative URL, to proxy to API server.
  return '/api' + path;
}

exports.default = function (store) {
  return function (next) {
    return function (action) {
      if (!action[CALL_API]) {
        return next(action);
      }
      var request = action[CALL_API];
      var getState = store.getState;

      var deferred = _bluebird2.default.defer();
      // handle 401 and auth here
      var method = request.method;
      var path = request.path;
      var types = request.types;
      var params = request.params;
      var tags = request.tags;

      var _types = _slicedToArray(types, 2);

      var successType = _types[0];
      var failureType = _types[1];


      var callback = function callback(err, res) {
        if (res && res.text) {
          if (res.ok) {
            next({
              type: successType,
              response: res,
              tags: tags || []
            });
            if (_lodash2.default.isFunction(request.afterSuccess)) {
              request.afterSuccess({ getState: getState });
            }
          }
        } else {
          next({
            type: failureType,
            response: {},
            tags: tags || []
          });
        }
        deferred.resolve();
      };

      if (method === 'get') {
        _superagent2.default[method](formatUrl(path)).timeout(500).query(_qs2.default.stringify(params)).end(callback);
      } else {
        _superagent2.default[method](formatUrl(path)).timeout(500).send(params).end(callback);
      }
      return deferred.promise;
    };
  };
};