'use strict';

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

var _keys = require('babel-runtime/core-js/object/keys');

var _keys2 = _interopRequireDefault(_keys);

var _reselect = require('reselect');

var _randombytes = require('randombytes');

var _randombytes2 = _interopRequireDefault(_randombytes);

var _field_analysis = require('./field_analysis');

var _field_analysis2 = _interopRequireDefault(_field_analysis);

var _filter_helpers = require('../util/filter_helpers');

var _flattened_features = require('./flattened_features');

var _flattened_features2 = _interopRequireDefault(_flattened_features);

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

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

// TODO: Create id based on hash of feature for consistency?
function uniqueId(f) {
  return (0, _randombytes2.default)(8).toString('hex');
}

/**
 * Flattens arrays, converts dates to numbers, and ensures each feature has an id
 */
var getFilterableFeatures = (0, _reselect.createSelector)(_flattened_features2.default, _field_analysis2.default, function (features, fieldAnalysis) {
  var idFieldNames = (0, _keys2.default)(fieldAnalysis.properties).filter(function (fieldName) {
    return fieldAnalysis.properties[fieldName].isUnique;
  });
  return features.map(function (f) {
    var i = void 0;
    var field = void 0;
    var value = void 0;
    var newProps = {};

    for (var fieldName in fieldAnalysis.properties) {
      field = fieldAnalysis.properties[fieldName];
      value = f.properties[fieldName];
      if (typeof value === 'undefined') {
        newProps[fieldName] = _constants.UNDEFINED_KEY;
        continue;
      }
      if ((0, _filter_helpers.isArrayLike)(field.type)) {
        // We can't filter arrays, so we flatten them
        if (!Array.isArray(value)) {
          // for fields which are a mix of arrays and numbers/strings
          newProps[fieldName + '.0'] = value;
        } else {
          for (i = 0; i < value.length; i++) {
            newProps[fieldName + '.' + i] = value[i];
          }
        }
      } else if (field.type === _constants.FIELD_TYPE_DATE) {
        // Convert dates to numbers so they can be filtered and sorted
        newProps[fieldName] = +(0, _filter_helpers.parseDate)(value);
      } else {
        newProps[fieldName] = value;
      }
    }

    var id = fieldAnalysis.$id.isUnique ? f.id : idFieldNames.length ? f.properties[idFieldNames[0]] : uniqueId(f);

    return {
      type: f.type,
      geometry: f.geometry,
      properties: newProps,
      id: id
    };
  });
});

exports.default = getFilterableFeatures;
//# sourceMappingURL=filterable_features.js.map