"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AnalyticsCollectionExploreTableLogic = void 0;
var _kea = require("kea");
var _common = require("@kbn/data-plugin/common");
var _kibana_logic = require("../../../shared/kibana/kibana_logic");
var _analytics_collection_data_view_logic = require("./analytics_collection_data_view_logic");
var _analytics_collection_explore_table_formulas = require("./analytics_collection_explore_table_formulas");
var _analytics_collection_explore_table_types = require("./analytics_collection_explore_table_types");
var _analytics_collection_toolbar_logic = require("./analytics_collection_toolbar/analytics_collection_toolbar_logic");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const BASE_PAGE_SIZE = 10;
const SEARCH_COOLDOWN = 200;
const tablesParams = {
  [_analytics_collection_explore_table_types.ExploreTables.SearchTerms]: {
    parseResponse: response => {
      var _response$rawResponse, _response$rawResponse2;
      return {
        items: ((_response$rawResponse = response.rawResponse.aggregations) === null || _response$rawResponse === void 0 ? void 0 : _response$rawResponse.searches.buckets.map(bucket => ({
          [_analytics_collection_explore_table_types.ExploreTableColumns.count]: bucket.doc_count,
          [_analytics_collection_explore_table_types.ExploreTableColumns.searchTerms]: bucket.key
        }))) || [],
        totalCount: ((_response$rawResponse2 = response.rawResponse.aggregations) === null || _response$rawResponse2 === void 0 ? void 0 : _response$rawResponse2.totalCount.value) || 0
      };
    },
    requestParams: (dataView, {
      timeRange,
      sorting,
      pageIndex,
      pageSize,
      search
    }, aggregationFieldName = 'search.query') => (0, _analytics_collection_explore_table_formulas.getBaseSearchTemplate)(dataView, aggregationFieldName, {
      eventType: 'search',
      search,
      timeRange
    }, {
      searches: {
        terms: {
          ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestSizeParams)(pageIndex, pageSize),
          field: aggregationFieldName,
          order: sorting ? {
            [sorting.field === _analytics_collection_explore_table_types.ExploreTableColumns.count ? '_count' : '_key']: sorting.direction
          } : undefined
        },
        ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestParams)(pageIndex, pageSize)
      },
      ...(0, _analytics_collection_explore_table_formulas.getTotalCountRequestParams)(aggregationFieldName)
    })
  },
  [_analytics_collection_explore_table_types.ExploreTables.WorsePerformers]: {
    parseResponse: response => {
      var _response$rawResponse3, _response$rawResponse4;
      return {
        items: ((_response$rawResponse3 = response.rawResponse.aggregations) === null || _response$rawResponse3 === void 0 ? void 0 : _response$rawResponse3.formula.searches.buckets.map(bucket => ({
          [_analytics_collection_explore_table_types.ExploreTableColumns.count]: bucket.doc_count,
          [_analytics_collection_explore_table_types.ExploreTableColumns.query]: bucket.key
        }))) || [],
        totalCount: ((_response$rawResponse4 = response.rawResponse.aggregations) === null || _response$rawResponse4 === void 0 ? void 0 : _response$rawResponse4.formula.totalCount.value) || 0
      };
    },
    requestParams: (dataView, {
      timeRange,
      sorting,
      pageIndex,
      pageSize,
      search
    }, aggregationFieldName = 'search.query') => (0, _analytics_collection_explore_table_formulas.getBaseSearchTemplate)(dataView, aggregationFieldName, {
      eventType: 'search',
      search,
      timeRange
    }, {
      formula: {
        aggs: {
          ...(0, _analytics_collection_explore_table_formulas.getTotalCountRequestParams)(aggregationFieldName),
          searches: {
            terms: {
              ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestSizeParams)(pageIndex, pageSize),
              field: aggregationFieldName,
              order: sorting ? {
                [(sorting === null || sorting === void 0 ? void 0 : sorting.field) === _analytics_collection_explore_table_types.ExploreTableColumns.count ? '_count' : '_key']: sorting === null || sorting === void 0 ? void 0 : sorting.direction
              } : undefined
            },
            ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestParams)(pageIndex, pageSize)
          }
        },
        filter: {
          term: {
            'search.results.total_results': '0'
          }
        }
      }
    })
  },
  [_analytics_collection_explore_table_types.ExploreTables.Clicked]: {
    parseResponse: response => {
      var _response$rawResponse5, _response$rawResponse6;
      return {
        items: ((_response$rawResponse5 = response.rawResponse.aggregations) === null || _response$rawResponse5 === void 0 ? void 0 : _response$rawResponse5.formula.searches.buckets.map(bucket => ({
          [_analytics_collection_explore_table_types.ExploreTableColumns.count]: bucket.doc_count,
          [_analytics_collection_explore_table_types.ExploreTableColumns.page]: bucket.key
        }))) || [],
        totalCount: ((_response$rawResponse6 = response.rawResponse.aggregations) === null || _response$rawResponse6 === void 0 ? void 0 : _response$rawResponse6.formula.totalCount.value) || 0
      };
    },
    requestParams: (dataView, {
      timeRange,
      sorting,
      pageIndex,
      pageSize,
      search
    }, aggregationFieldName = 'page.url.original') => (0, _analytics_collection_explore_table_formulas.getBaseSearchTemplate)(dataView, aggregationFieldName, {
      eventType: 'search_click',
      search,
      timeRange
    }, {
      formula: {
        aggs: {
          ...(0, _analytics_collection_explore_table_formulas.getTotalCountRequestParams)(aggregationFieldName),
          searches: {
            terms: {
              ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestSizeParams)(pageIndex, pageSize),
              field: aggregationFieldName,
              order: sorting ? {
                [sorting.field === _analytics_collection_explore_table_types.ExploreTableColumns.count ? '_count' : '_key']: sorting.direction
              } : undefined
            },
            ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestParams)(pageIndex, pageSize)
          }
        },
        filter: {
          term: {
            'event.action': 'search_click'
          }
        }
      }
    })
  },
  [_analytics_collection_explore_table_types.ExploreTables.Referrers]: {
    parseResponse: response => {
      var _response$rawResponse7, _response$rawResponse8;
      return {
        items: ((_response$rawResponse7 = response.rawResponse.aggregations) === null || _response$rawResponse7 === void 0 ? void 0 : _response$rawResponse7.formula.searches.buckets.map(bucket => ({
          [_analytics_collection_explore_table_types.ExploreTableColumns.sessions]: bucket.doc_count,
          [_analytics_collection_explore_table_types.ExploreTableColumns.page]: bucket.key
        }))) || [],
        totalCount: ((_response$rawResponse8 = response.rawResponse.aggregations) === null || _response$rawResponse8 === void 0 ? void 0 : _response$rawResponse8.formula.totalCount.value) || 0
      };
    },
    requestParams: (dataView, {
      timeRange,
      sorting,
      pageIndex,
      pageSize,
      search
    }, aggregationFieldName = 'page.referrer.original') => (0, _analytics_collection_explore_table_formulas.getBaseSearchTemplate)(dataView, aggregationFieldName, {
      eventType: 'page_view',
      search,
      timeRange
    }, {
      formula: {
        aggs: {
          ...(0, _analytics_collection_explore_table_formulas.getTotalCountRequestParams)(aggregationFieldName),
          searches: {
            terms: {
              ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestSizeParams)(pageIndex, pageSize),
              field: aggregationFieldName,
              order: sorting ? {
                [(sorting === null || sorting === void 0 ? void 0 : sorting.field) === _analytics_collection_explore_table_types.ExploreTableColumns.sessions ? '_count' : '_key']: sorting === null || sorting === void 0 ? void 0 : sorting.direction
              } : undefined
            },
            ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestParams)(pageIndex, pageSize)
          }
        },
        filter: {
          term: {
            'event.action': 'page_view'
          }
        }
      }
    })
  },
  [_analytics_collection_explore_table_types.ExploreTables.Locations]: {
    parseResponse: response => {
      var _response$rawResponse9, _response$rawResponse10;
      return {
        items: ((_response$rawResponse9 = response.rawResponse.aggregations) === null || _response$rawResponse9 === void 0 ? void 0 : _response$rawResponse9.formula.searches.buckets.map(bucket => ({
          [_analytics_collection_explore_table_types.ExploreTableColumns.sessions]: bucket.doc_count,
          [_analytics_collection_explore_table_types.ExploreTableColumns.location]: bucket.key[0],
          countryISOCode: bucket.key[1]
        }))) || [],
        totalCount: ((_response$rawResponse10 = response.rawResponse.aggregations) === null || _response$rawResponse10 === void 0 ? void 0 : _response$rawResponse10.formula.totalCount.value) || 0
      };
    },
    requestParams: (dataView, {
      timeRange,
      sorting,
      pageIndex,
      pageSize,
      search
    }, aggregationFieldName = 'session.location.country_name') => (0, _analytics_collection_explore_table_formulas.getBaseSearchTemplate)(dataView, aggregationFieldName, {
      search,
      timeRange
    }, {
      formula: {
        aggs: {
          ...(0, _analytics_collection_explore_table_formulas.getTotalCountRequestParams)(aggregationFieldName),
          searches: {
            multi_terms: {
              ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestSizeParams)(pageIndex, pageSize),
              order: sorting ? {
                [(sorting === null || sorting === void 0 ? void 0 : sorting.field) === _analytics_collection_explore_table_types.ExploreTableColumns.sessions ? '_count' : '_key']: sorting === null || sorting === void 0 ? void 0 : sorting.direction
              } : undefined,
              terms: [{
                field: aggregationFieldName
              }, {
                field: 'session.location.country_iso_code'
              }]
            },
            ...(0, _analytics_collection_explore_table_formulas.getPaginationRequestParams)(pageIndex, pageSize)
          }
        },
        filter: {
          term: {
            'event.action': 'page_view'
          }
        }
      }
    })
  }
};
const AnalyticsCollectionExploreTableLogic = (0, _kea.kea)({
  actions: {
    onTableChange: ({
      page,
      sort
    }) => ({
      page,
      sort
    }),
    reset: true,
    setItems: items => ({
      items
    }),
    setSearch: search => ({
      search
    }),
    setSelectedTable: (id, sorting) => ({
      id,
      sorting
    }),
    setTotalItemsCount: count => ({
      count
    })
  },
  connect: {
    actions: [_analytics_collection_toolbar_logic.AnalyticsCollectionToolbarLogic, ['setTimeRange', 'setSearchSessionId'], _analytics_collection_data_view_logic.AnalyticsCollectionDataViewLogic, ['setDataView']],
    values: [_analytics_collection_data_view_logic.AnalyticsCollectionDataViewLogic, ['dataView'], _analytics_collection_toolbar_logic.AnalyticsCollectionToolbarLogic, ['timeRange', 'searchSessionId']]
  },
  listeners: ({
    actions,
    values
  }) => {
    const fetchItems = () => {
      if (values.selectedTable === null || !(values.selectedTable in tablesParams) || !values.dataView) {
        actions.setItems([]);
        actions.setTotalItemsCount(0);
        return;
      }
      const {
        requestParams,
        parseResponse
      } = tablesParams[values.selectedTable];
      const timeRange = values.timeRange;
      const search$ = _kibana_logic.KibanaLogic.values.data.search.search(requestParams(values.dataView, {
        pageIndex: values.pageIndex,
        pageSize: values.pageSize,
        search: values.search,
        sorting: values.sorting,
        timeRange
      }), {
        indexPattern: values.dataView,
        sessionId: values.searchSessionId
      }).subscribe({
        error: e => {
          _kibana_logic.KibanaLogic.values.data.search.showError(e);
        },
        next: response => {
          if (!(0, _common.isRunningResponse)(response)) {
            const {
              items,
              totalCount
            } = parseResponse(response);
            actions.setItems(items);
            actions.setTotalItemsCount(totalCount);
            search$.unsubscribe();
          }
        }
      });
    };
    return {
      onTableChange: fetchItems,
      setDataView: fetchItems,
      setSearch: async (_, breakpoint) => {
        await breakpoint(SEARCH_COOLDOWN);
        fetchItems();
      },
      setSearchSessionId: fetchItems,
      setSelectedTable: fetchItems,
      setTimeRange: fetchItems
    };
  },
  path: ['enterprise_search', 'analytics', 'collection', 'explore', 'table'],
  reducers: () => ({
    isLoading: [false, {
      onTableChange: () => true,
      setItems: () => false,
      setSearch: () => true,
      setSearchSessionId: () => true,
      setSelectedTable: () => true,
      setTableState: () => true,
      setTimeRange: () => true
    }],
    items: [[], {
      setItems: (_, {
        items
      }) => items
    }],
    pageIndex: [0, {
      onTableChange: (_, {
        page
      }) => (page === null || page === void 0 ? void 0 : page.index) || 0,
      reset: () => 0,
      setSearch: () => 0,
      setSelectedTable: () => 0
    }],
    pageSize: [BASE_PAGE_SIZE, {
      onTableChange: (_, {
        page
      }) => (page === null || page === void 0 ? void 0 : page.size) || BASE_PAGE_SIZE,
      reset: () => BASE_PAGE_SIZE
    }],
    search: ['', {
      reset: () => '',
      setSearch: (_, {
        search
      }) => search,
      setSelectedTable: () => ''
    }],
    selectedTable: [null, {
      setSelectedTable: (_, {
        id
      }) => id
    }],
    sorting: [null, {
      onTableChange: (_, {
        sort = null
      }) => sort,
      setSelectedTable: (_, {
        sorting = null
      }) => sorting
    }],
    totalItemsCount: [0, {
      setTotalItemsCount: (_, {
        count
      }) => count
    }]
  })
});
exports.AnalyticsCollectionExploreTableLogic = AnalyticsCollectionExploreTableLogic;