import { mlFunctionToESAggregation } from '../../../common/util/job_utils' ; import { getDataViewById , getDataViewIdFromName } from '../util/index_utils' ; import { mlJobService } from './job_service' ; import type { DataView } from '../../../../../../src/plugins/data_views/public' ; type FormatsByJobId = Record < string , any > ; type IndexPatternIdsByJob = Record < string , any > ; class FieldFormatService { indexPatternIdsByJob : IndexPatternIdsByJob = { } ; formatsByJob : FormatsByJobId = { } ; async populateFormats ( jobIds ) { ( await Promise . all ( jobIds . map ( async ( jobId ) => { const jobObj = mlJobService . getJob ( jobId ) ; return { jobId , dataViewId : await getDataViewIdFromName ( jobObj . datafeed_config . indices . join ( ',' ) ) , } ; } ) ) ) . forEach ( ( { jobId , dataViewId } ) => { if ( dataViewId !== null ) { this . indexPatternIdsByJob [ jobId ] = dataViewId ; } } ) ; const promises = jobIds . map ( ( jobId ) => Promise . all ( [ this . getFormatsForJob ( jobId ) ] ) ) ; try { const fmtsByJobByDetector = await Promise . all ( promises ) ; fmtsByJobByDetector . forEach ( ( formatsByDetector , i ) => { this . formatsByJob [ jobIds [ i ] ] = formatsByDetector [ 0 ] ; } ) ; return this . formatsByJob ; } catch ( error ) { console . log ( 'Error populating field formats:' , error ) ; return { formats : { } , error } ; } } getFieldFormat ( jobId , detectorIndex ) { if ( this . formatsByJob . hasOwnProperty ( jobId ) ) { return this . formatsByJob [ jobId ] [ detectorIndex ] ; } } getFieldFormatFromIndexPattern ( fullIndexPattern , fieldName , esAggName ) { let fieldFormat ; if ( esAggName !== 'cardinality' ) { const fieldList = fullIndexPattern . fields ; const field = fieldList . getByName ( fieldName ) ; if ( field !== undefined ) { fieldFormat = fullIndexPattern . getFormatterForField ( field ) ; } } return fieldFormat ; } getFormatsForJob ( jobId ) { return new Promise ( ( resolve , reject ) => { const jobObj = mlJobService . getJob ( jobId ) ; const detectors = jobObj . analysis_config . detectors || [ ] ; const formatsByDetector = [ ] ; const dataViewId = this . indexPatternIdsByJob [ jobId ] ; if ( dataViewId !== undefined ) { getDataViewById ( dataViewId ) . then ( ( dataView ) => { const fieldList = dataView . fields ; detectors . forEach ( ( dtr ) => { const esAgg = mlFunctionToESAggregation ( dtr . function ) ; if ( dtr . field_name !== undefined && esAgg !== 'cardinality' ) { const field = fieldList . getByName ( dtr . field_name ) ; if ( field !== undefined ) { formatsByDetector [ dtr . detector_index ! ] = dataView . getFormatterForField ( field ) ; } } } ) ; resolve ( formatsByDetector ) ; } ) . catch ( ( err ) => { reject ( err ) ; } ) ; } else { resolve ( formatsByDetector ) ; } } ) ; } } export const mlFieldFormatService = new FieldFormatService ( ) ;