'use strict';

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

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

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

var _keys2 = _interopRequireDefault(_keys);

var _reselect = require('reselect');

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

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

var _field_analysis2 = _interopRequireDefault(_field_analysis);

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

/**
 * Builds a valid mapbox-gl filter expression our filters, which
 * are organized by key.
 * @example
 * ```
 * getMapboxFilter({foo: {in: ['bar', 'baz']}, qux: {'>=': 1, '<=': 3}})
 * // ['all', ['in', 'foo', bar', 'baz'], ['all', ['>=', 'qux', 1], ['<=', 'qux', 3]]]
 * ```
 * @param {object} filtersByField
 * @return {array} valid mapbox-gl filter
 */
var getMapboxFilter = (0, _reselect.createSelector)(function (state) {
  return state.filters;
}, _field_analysis2.default, function (filters, fieldAnalysis) {
  return (0, _keys2.default)(filters).reduce(function (p, f) {
    var exp = filters[f];
    if (!fieldAnalysis.properties[f]) return p;
    if (exp.in) {
      if (fieldAnalysis.properties[f] && (0, _filter_helpers.isArrayLike)(fieldAnalysis.properties[f].type)) {
        var subFilter = ['any', ['in', f].concat((0, _toConsumableArray3.default)(exp.in))];
        for (var i = 0; i < fieldAnalysis.properties[f].maxArrayLength; i++) {
          subFilter.push(['in', f + '.' + i].concat((0, _toConsumableArray3.default)(exp.in)));
        }
        p.push(subFilter);
      } else {
        p.push(['in', f].concat((0, _toConsumableArray3.default)(exp.in)));
      }
    } else if (exp['<='] || exp['>=']) {
      var compoundExp = ['all'];
      if (exp['<=']) compoundExp.push(['<=', f, exp['<=']]);
      if (exp['>=']) compoundExp.push(['>=', f, exp['>=']]);
      p.push(compoundExp);
    }
    return p;
  }, ['all']);
});

exports.default = getMapboxFilter;
//# sourceMappingURL=mapbox_filter.js.map