import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import pick from 'lodash/pick';
import { deburrUpper } from 'app/utils';

const getModel = data => data.model || null;
const getModelData = espData =>
  (espData.modelData && !isEmpty(espData.modelData.data)
    ? espData.modelData.data
    : null);

const getQuery = data => deburrUpper(data.query) || '';

export const filteredModelData = createSelector(
  [getModelData, getModel],
  (data, model) => {
    if (!data) return null;
    const modelWhiteListedFields = {
      Models: [
        'full_name',
        'abbreviation',
        'availability',
        'current_version',
        'development_year',
        'expertise',
        'license',
        'maintainer_name'
      ],
      Scenarios: [
        'name',
        'model_abbreviation',
        'category',
        'geographic_coverage_country',
        'geographic_coverage_region',
        'purpose_or_objective',
        'time_horizon'
      ],
      Indicators: ['name', 'category', 'subcategory', 'definition', 'unit']
    };
    return data.map(d => pick(d, modelWhiteListedFields[model]));
  }
);

export const filteredDataBySearch = createSelector(
  [filteredModelData, getQuery],
  (data, query) => {
    if (!data) return null;
    if (!query) return data;

    return data.filter(d =>
      Object.keys(d).some(key => {
        if (Object.prototype.hasOwnProperty.call(d, key) && d[key] !== null) {
          return deburrUpper(d[key]).indexOf(query) > -1;
        }
        return false;
      })
    );
  }
);

export default {
  filteredDataBySearch
};

@@ -178,21 +178,24 @@
 =%3E data.
-model
+category
  %7C%7C null
@@ -235,29 +235,32 @@
 %0A  (espData.
-model
+category
 Data && !isE
@@ -264,37 +264,40 @@
 isEmpty(espData.
-model
+category
 Data.data)%0A    ?
@@ -305,21 +305,24 @@
 espData.
-model
+category
 Data.dat
@@ -480,21 +480,24 @@
  (data, 
-model
+category
 ) =%3E %7B%0A 
@@ -533,21 +533,24 @@
   const 
-model
+category
 WhiteLis
@@ -822,21 +822,24 @@
        '
-model
+category
 _abbrevi
@@ -1123,21 +1123,24 @@
 pick(d, 
-model
+category
 WhiteLis
@@ -1153,13 +1153,16 @@
 lds%5B
-model
+category
 %5D));

Rename model to category part II