"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = mergeProps;

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

var _classnames = _interopRequireDefault(require("classnames"));

var _isPromise = _interopRequireDefault(require("is-promise"));

var _isNil = _interopRequireDefault(require("lodash/isNil"));

var _isFunction = _interopRequireDefault(require("lodash/isFunction"));

var _assignWith = _interopRequireDefault(require("lodash/assignWith"));

var _shared = require("choerodon-ui/shared");

if (!_shared.global.FUNCTION_CHAINS_MAP) {
  _shared.global.FUNCTION_CHAINS_MAP = new WeakMap();
}

var chainsMap = _shared.global.FUNCTION_CHAINS_MAP;

function merge(prop, other) {
  if ((0, _isNil["default"])(prop)) {
    return other;
  }

  if ((0, _isNil["default"])(other)) {
    return prop;
  }

  return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, prop), other);
}

function customizer(value, srcValue, key) {
  if (key === 'style' || key.endsWith('Style')) {
    return merge(value, srcValue);
  }

  if (key === 'className' || key.endsWith('ClassName')) {
    return (0, _classnames["default"])(value, srcValue);
  }

  if (key.endsWith('Props')) {
    return mergeProps(value, srcValue);
  }

  if ((0, _isFunction["default"])(value) && (0, _isFunction["default"])(srcValue)) {
    var chains = chainsMap.get(value);

    if (chains) {
      chains.fn = srcValue;
      return chains;
    }

    var newChains = function newChains() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var $chains = chainsMap.get(value);

      var _ref = $chains || {},
          fn = _ref.fn;

      if (fn) {
        var ret = fn.apply(void 0, args);

        if ((0, _isPromise["default"])(ret)) {
          return ret.then(function (result) {
            if (result !== false) {
              return value.apply(void 0, args);
            }

            return result;
          });
        }

        if (ret === false) {
          return false;
        }
      }

      return value.apply(void 0, args);
    };

    newChains.fn = srcValue;
    chainsMap.set(value, newChains);
    return newChains;
  }
}

function mergeProps(props, otherProps) {
  if ((0, _isNil["default"])(props)) {
    return otherProps;
  }

  if ((0, _isNil["default"])(otherProps)) {
    return props;
  }

  return (0, _assignWith["default"])(props, otherProps, customizer);
}
//# sourceMappingURL=mergeProps.js.map
