"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactApollo = require("react-apollo");

var _get = _interopRequireDefault(require("lodash/get"));

var _helpers = require("../helpers");

var _default = function _default(_ref) {
  var _ref$config = _ref.config,
      config = _ref$config === void 0 ? function () {} : _ref$config,
      mutationName = _ref.mutationName,
      mutation = _ref.mutation,
      defaultPropName = _ref.defaultPropName;

  var getPropName = function getPropName(props) {
    var params = config(props);
    return (0, _get.default)(params, "name", defaultPropName);
  };

  return (0, _reactApollo.graphql)(mutation, {
    props: function props(_ref2) {
      var mutate = _ref2.mutate,
          ownProps = _ref2.ownProps;
      var propName = getPropName(ownProps);
      return (0, _defineProperty2.default)({}, propName, function () {
        var _ref3 = (0, _asyncToGenerator2.default)(
        /*#__PURE__*/
        _regenerator.default.mark(function _callee(params) {
          var res, parsedRes;
          return _regenerator.default.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  _context.next = 2;
                  return mutate({
                    variables: params
                  });

                case 2:
                  res = _context.sent;
                  parsedRes = _helpers.graphqlResponse.handleMutationResponse(res, mutationName);

                  if (!parsedRes.success) {
                    _context.next = 6;
                    break;
                  }

                  return _context.abrupt("return", {
                    error: null,
                    success: true,
                    result: parsedRes.result
                  });

                case 6:
                  return _context.abrupt("return", {
                    error: (0, _get.default)(parsedRes, "error") || [],
                    success: false,
                    result: parsedRes.result
                  });

                case 7:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee, this);
        }));

        return function (_x) {
          return _ref3.apply(this, arguments);
        };
      }());
    }
  });
};

exports.default = _default;