import { computed, makeObservable } from 'mobx'; import { FiltersMap, withoutDefaults } from '@wix/bex-core'; import { cairoSearchViewInViews } from '@wix/bex-core/bi'; import { ViewsLocalSearchState } from './ViewsLocalSearchState'; import { EventEmitter } from 'events'; import { TypedEmitter } from '@wix/bex-core/events'; import { addEventListener } from '@wix/bex-core/util'; import { cairoSearchViewInViewsParams as SearchViewInViewsParams } from '@wix/bex-utils/@wix/bi-logger-os-data/v2/types'; export interface ViewsLocalSearchBIReporterParams { readonly state: ViewsLocalSearchState; } export class ViewsLocalSearchBIReporter { readonly state; readonly events = new EventEmitter() as TypedEmitter<{ blur: () => unknown; afterSelectView: () => unknown; }>; get views() { return this.state.views; } get reportBI() { return this.views.reportBI; } constructor(params: ViewsLocalSearchBIReporterParams) { this.state = params.state; makeObservable(this, { totalViews: computed, totalFilteredViewsAndCategories: computed, totalFilteredCategories: computed, }); } _clearAllEvents() { const { events } = this; events.removeAllListeners('afterSelectView'); events.removeAllListeners('blur'); } onSearch() { const { events, state } = this; const afterSearchParams = { numViews: this.totalViews, searchResultsCnt: this.totalFilteredViewsAndCategories, numCategoriesInResults: this.totalFilteredCategories, searchTerm: state.localSearchValue, } as Partial; const reportViewSelectedSearchBI = () => { this._clearAllEvents(); this.reportBI( withoutDefaults(cairoSearchViewInViews)({ ...afterSearchParams, endType: 'View selected', }), ); }; const reportSearchDismissedSearchBI = () => { this._clearAllEvents(); this.reportBI( withoutDefaults(cairoSearchViewInViews)({ ...afterSearchParams, endType: 'Search dismissed', }), ); }; this._clearAllEvents(); events.once('afterSelectView', reportViewSelectedSearchBI); events.once('blur', reportSearchDismissedSearchBI); } get totalViews() { const { categoriesWithViews: { categories, viewsWithoutCategory }, } = this.state; return ( viewsWithoutCategory.length + categories.reduce((sum, category) => sum + category.views.length, 0) ); } get totalFilteredViewsAndCategories() { const { filteredCategoriesWithViews: { categories, viewsWithoutCategory }, } = this.state; return ( viewsWithoutCategory.length + categories.length + categories.reduce((sum, category) => sum + category.views.length, 0) ); } get totalFilteredCategories() { const { filteredCategoriesWithViews: { categories }, } = this.state; return categories.length; } init() { const { views, events } = this; const { autoCompleteReadonlyState } = views; const disposers = [ addEventListener(views.events, 'afterSelectView', () => { events.emit('afterSelectView'); }), addEventListener(autoCompleteReadonlyState.events, 'blur', () => { events.emit('blur'); }), ]; return () => { disposers.forEach((d) => d()); }; } }