'use strict';

const getWrappedValue = (data, fieldId) => {
  let dataWrapper = data;
  fieldId.split('.').forEach(key => {
    if (!dataWrapper) {
      return;
    }
    dataWrapper = dataWrapper[key];
  });
  return dataWrapper;
};
/**
 * Returns the display value for the field.
 * @param model
 * @param field
 * @param fieldId is used if the value is wrapped. Ex: { field: 'user', fieldId: 'user.firstName' }
 */
const getDataModelFieldDisplayValue = (model, field, fieldId) => {
  var _a;
  if ((fieldId === 'name' || (field === null || field === void 0 ? void 0 : field.id) === 'name') && !model.name) {
    // TODO find a proper way to process special fields
    return `${model.user.firstName} ${model.user.lastName}`;
  }
  if (fieldId === null || fieldId === void 0 ? void 0 : fieldId.includes('.')) {
    return getWrappedValue(model, fieldId);
  }
  else if ((_a = field === null || field === void 0 ? void 0 : field.id) === null || _a === void 0 ? void 0 : _a.includes('.')) {
    return getWrappedValue(model, field.id);
  }
  if (!field) {
    // i don't know any scenario fitting this but it's better than just returning undefined
    return model[fieldId];
  }
  return model[field.id];
};
function getDataModelField(model, fieldId) {
  return model[fieldId];
}
class DataModel {
  static decode(json) {
    return Object.assign(Object.create(DataModel.prototype), json);
  }
  toObject() {
    return JSON.parse(JSON.stringify(this));
  }
  toDBRef(collection) {
    return {
      _ref: collection,
      _id: this._id,
    };
  }
}
DataModel.decodeList = (data = []) => {
  return data.map(item => DataModel.decode(item));
};

exports.DataModel = DataModel;
exports.getDataModelField = getDataModelField;
exports.getDataModelFieldDisplayValue = getDataModelFieldDisplayValue;
