"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
exports.get = get;
exports.remove = remove;
exports.set = set;

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _mobx = require("mobx");

var _mobxHelper = require("../mobx-helper");

function get(obj, prop) {
  if (obj === null) {
    return null;
  }

  if (obj !== undefined) {
    var index = prop.indexOf('.');

    if (index !== -1) {
      var key = prop.slice(0, index);
      var restKey = prop.slice(index + 1);
      var value = (0, _mobxHelper.mobxGet)(obj, key);

      if (value === null) {
        return null;
      }

      if ((0, _mobx.isArrayLike)(value)) {
        return value.map(function (item) {
          return get(item, restKey);
        }).filter(function (item) {
          return !!item || item === false || item === 0;
        });
      }

      if ((0, _isObject["default"])(value)) {
        return get(value, restKey);
      }
    } else {
      return (0, _mobxHelper.mobxGet)(obj, prop);
    }
  }
}

function set(data, prop, value) {
  var fields = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _mobx.observable.map();
  var record = arguments.length > 4 ? arguments[4] : undefined;
  var index = prop.indexOf('.');

  if (index !== -1) {
    var key = prop.slice(0, index);

    if (!data[key] && value !== undefined) {
      var field = fields.get(key);

      if (field && field.get('multiple', record)) {
        (0, _mobxHelper.mobxSet)(data, key, []);
      } else {
        (0, _mobxHelper.mobxSet)(data, key, {});
      }
    }

    var obj = (0, _mobxHelper.mobxGet)(data, key);

    if ((0, _mobx.isArrayLike)(obj)) {
      if ((0, _mobx.isArrayLike)(value)) {
        value.forEach(function (item, i) {
          if (obj.length === i) {
            obj.push({});
          } else if (!obj[i]) {
            obj[i] = {};
          }

          set(obj[i], prop.slice(index + 1), item);
        });
      }
    } else if ((0, _isObject["default"])(obj)) {
      set(obj, prop.slice(index + 1), value);
    }
  } else {
    (0, _mobxHelper.mobxSet)(data, prop, value);
  }
}

function remove(obj, prop) {
  var index = prop.indexOf('.');

  if (index !== -1) {
    var value = (0, _mobxHelper.mobxGet)(obj, prop.slice(0, index));

    if (value) {
      var restKey = prop.slice(index + 1);

      if ((0, _mobx.isArrayLike)(value)) {
        value.forEach(function (item) {
          return remove(item, restKey);
        });
      } else if ((0, _isObject["default"])(value)) {
        remove(value, restKey);
      }
    }
  } else {
    (0, _mobxHelper.mobxRemove)(obj, prop);
  }
}

var _default = {
  get: get,
  set: set,
  remove: remove
};
exports["default"] = _default;
//# sourceMappingURL=index.js.map
