'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _nodeBits = require('node-bits');

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var MediaSubscriber = function () {
  function MediaSubscriber(config) {
    _classCallCheck(this, MediaSubscriber);

    this.storage = config.storage;
  }

  _createClass(MediaSubscriber, [{
    key: 'subscribe',
    value: function subscribe() {
      return true;
    }
  }, {
    key: 'perform',
    value: function perform(args) {
      var _this = this;

      var req = args.req,
          stage = args.stage,
          verb = args.verb;


      if (![_nodeBits.POST, _nodeBits.PUT].includes(verb) || stage !== _nodeBits.BEFORE) {
        return null;
      }

      return Promise.all(_lodash2.default.keys(req.files).map(function (key) {
        var file = req.files[key];
        var storeResult = _this.storage.store(file, key, args);

        var promise = Promise.resolve(storeResult);
        if (storeResult && storeResult.then) {
          promise = storeResult;
        }

        return promise.then(function (value) {
          req.body[key] = value;
        });
      }));
    }
  }]);

  return MediaSubscriber;
}();

exports.default = MediaSubscriber;