import _ from 'lodash' ; import { IFieldType , IIndexPattern , Filter , isExistsFilter , isPhraseFilter , getPhraseFilterValue , getPhraseFilterField , isScriptedPhraseFilter , buildFilter , FilterStateStore , FILTERS , } from '../../../../common' ; import { FilterManager } from '../filter_manager' ; function getExistingFilter ( appFilters , fieldName , value ) { return _ . find ( appFilters , function ( filter ) { if ( ! filter ) return ; if ( fieldName === '_exists_' && isExistsFilter ( filter ) ) { return filter . exists ! . field === value ; } if ( isPhraseFilter ( filter ) ) { return getPhraseFilterField ( filter ) === fieldName && getPhraseFilterValue ( filter ) === value ; } if ( isScriptedPhraseFilter ( filter ) ) { return filter . meta . field === fieldName && filter . script ! . script . params . value === value ; } } ) as any ; } function updateExistingFilter ( existingFilter , negate ) { existingFilter . meta . disabled = false ; if ( existingFilter . meta . negate !== negate ) { existingFilter . meta . negate = ! existingFilter . meta . negate ; } } param { FilterManager } filterManager param { Field | string } field param { any } values param { string } operation param { string } index returns { object } export function generateFilters ( filterManager , field , values , operation , index ) { values = Array . isArray ( values ) ? values : [ values ] ; const fieldObj = ( _ . isObject ( field ) ? field : { name : field , } ) as IFieldType ; const fieldName = fieldObj . name ; const newFilters = [ ] ; const appFilters = filterManager . getAppFilters ( ) ; const negate = operation === '-' ; let filter ; _ . each ( values , function ( value ) { const existing = getExistingFilter ( appFilters , fieldName , value ) ; if ( existing ) { updateExistingFilter ( existing , negate ) ; filter = existing ; } else { const tmpIndexPattern = { id : index } as IIndexPattern ; const filterType = fieldName === '_exists_' ? FILTERS . EXISTS : FILTERS . PHRASE ; const actualFieldObj = fieldName === '_exists_' ? ( { name : value } as IFieldType ) : fieldObj ; const isNullFilter = value === null || value === undefined ; filter = buildFilter ( tmpIndexPattern , actualFieldObj , isNullFilter ? FILTERS . EXISTS : filterType , isNullFilter ? ! negate : negate , false , value , null , FilterStateStore . APP_STATE ) ; } newFilters . push ( filter ) ; } ) ; return newFilters ; }