"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AnalyticsCollectionsLogic = void 0;
var _kea = require("kea");
var _api = require("../../../../../common/types/api");
var _fetch_analytics_collections_api_logic = require("../../api/index/fetch_analytics_collections_api_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 SEARCH_COOLDOWN = 200;
const AnalyticsCollectionsLogic = (0, _kea.kea)({
  actions: {
    fetchAnalyticsCollections: true,
    searchAnalyticsCollections: query => ({
      query
    })
  },
  connect: {
    actions: [_fetch_analytics_collections_api_logic.FetchAnalyticsCollectionsAPILogic, ['makeRequest']],
    values: [_fetch_analytics_collections_api_logic.FetchAnalyticsCollectionsAPILogic, ['data', 'status']]
  },
  listeners: ({
    actions
  }) => ({
    fetchAnalyticsCollections: () => {
      actions.makeRequest({});
    },
    searchAnalyticsCollections: async ({
      query
    }, breakpoint) => {
      if (query) {
        await breakpoint(SEARCH_COOLDOWN);
      }
      actions.makeRequest({
        query
      });
    }
  }),
  path: ['enterprise_search', 'analytics', 'collections'],
  reducers: {
    isSearchRequest: [false, {
      searchAnalyticsCollections: () => true
    }],
    searchQuery: ['', {
      searchAnalyticsCollections: (_, {
        query
      }) => query
    }]
  },
  selectors: ({
    selectors
  }) => ({
    analyticsCollections: [() => [selectors.data], data => data || []],
    hasNoAnalyticsCollections: [() => [selectors.analyticsCollections, selectors.searchQuery], (analyticsCollections, searchQuery) => analyticsCollections.length === 0 && !searchQuery],
    isFetching: [() => [selectors.status, selectors.isSearchRequest], (status, isSearchRequest) => [_api.Status.LOADING, _api.Status.IDLE].includes(status) && !isSearchRequest],
    isSearching: [() => [selectors.status, selectors.isSearchRequest], (status, isSearchRequest) => _api.Status.LOADING === status && isSearchRequest]
  })
});
exports.AnalyticsCollectionsLogic = AnalyticsCollectionsLogic;