'use strict';

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

var _reselect = require('reselect');

var _flat = require('../util/flat');

var _flat2 = _interopRequireDefault(_flat);

var _geojsonFlatten = require('geojson-flatten');

var _geojsonFlatten2 = _interopRequireDefault(_geojsonFlatten);

var _objectAssign = require('object-assign');

var _objectAssign2 = _interopRequireDefault(_objectAssign);

var _constants = require('../constants');

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

var isMultiGeometry = {
  MultiPoint: true,
  MultiPolygon: true,
  MultiLineString: true,
  GeometryCollection: true

  /**
   * Flatten nested props and flatten multi-geometries
   */
};var getFlattenedFeatures = (0, _reselect.createSelector)(function (state) {
  return state.features;
}, function (state) {
  return state.fieldTypes;
}, function (features, fieldTypes) {
  var withFlattenedProps;
  var withFlattenedGeom;
  var geomType;
  var flattenedFeatures = [];
  for (var i = 0; i < features.length; i++) {
    withFlattenedProps = (0, _objectAssign2.default)({}, features[i], {
      // Does not flatten arrays - we need to preserve them for field analysis
      properties: (0, _flat2.default)(features[i].properties, { safe: true })
    });
    expandDelimitedFields(withFlattenedProps.properties, fieldTypes);
    geomType = features[i].geometry && features[i].geometry.type;
    // geojson-flatten would (unnecessarily) clone properties of every feature,
    // even if not a multiGeometry, which would have a performance overhead.
    withFlattenedGeom = isMultiGeometry[geomType] ? (0, _geojsonFlatten2.default)(withFlattenedProps) : [withFlattenedProps];
    // Faster (mutates flattenedFeatures) vs. flattenedFeatues.concat() which would
    // creates new arrays which need garbage collected
    Array.prototype.push.apply(flattenedFeatures, withFlattenedGeom);
  }
  return flattenedFeatures;
});

// **Side effects**
function expandDelimitedFields(props, fieldTypes) {
  for (var key in props) {
    if (fieldTypes[key] !== _constants.FIELD_TYPE_SPACE_DELIMITED) continue;
    if (typeof props[key] !== 'string') continue;
    props[key] = props[key].split(' ');
  }
}

exports.default = getFlattenedFeatures;
//# sourceMappingURL=flattened_features.js.map