"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ApiLogsLogic = void 0;
var _kea = require("kea");
var _constants = require("../../../shared/constants");
var _flash_messages = require("../../../shared/flash_messages");
var _http = require("../../../shared/http");
var _table_pagination = require("../../../shared/table_pagination");
var _engine = require("../engine");
var _constants2 = require("./constants");
var _utils = require("./utils");
/*
 * 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 ApiLogsLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'app_search', 'api_logs_logic'],
  actions: () => ({
    fetchApiLogs: ({
      isPoll
    } = {
      isPoll: false
    }) => ({
      isPoll
    }),
    pollForApiLogs: true,
    onPollStart: intervalId => ({
      intervalId
    }),
    onPollInterval: ({
      results,
      meta
    }) => ({
      results,
      meta
    }),
    storePolledData: ({
      results,
      meta
    }) => ({
      results,
      meta
    }),
    updateView: ({
      results,
      meta
    }) => ({
      results,
      meta
    }),
    onUserRefresh: true,
    onPaginate: newPageIndex => ({
      newPageIndex
    })
  }),
  reducers: () => ({
    dataLoading: [true, {
      updateView: () => false,
      onPaginate: () => true
    }],
    apiLogs: [[], {
      updateView: (_, {
        results
      }) => results
    }],
    meta: [_constants.DEFAULT_META, {
      updateView: (_, {
        meta
      }) => meta,
      onPaginate: (state, {
        newPageIndex
      }) => (0, _table_pagination.updateMetaPageIndex)(state, newPageIndex)
    }],
    hasNewData: [false, {
      storePolledData: () => true,
      updateView: () => false
    }],
    polledData: [{}, {
      storePolledData: (_, data) => data
    }],
    intervalId: [null, {
      onPollStart: (_, {
        intervalId
      }) => intervalId
    }]
  }),
  listeners: ({
    actions,
    values
  }) => ({
    pollForApiLogs: () => {
      if (values.intervalId) return; // Ensure we only have one poll at a time

      const id = window.setInterval(() => actions.fetchApiLogs({
        isPoll: true
      }), _constants2.POLLING_DURATION);
      actions.onPollStart(id);
    },
    fetchApiLogs: async ({
      isPoll
    }) => {
      if (isPoll && values.dataLoading) return; // Manual fetches (i.e. user pagination) should override polling

      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      try {
        const response = await http.get(`/internal/app_search/engines/${engineName}/api_logs`, {
          query: {
            'page[current]': values.meta.page.current,
            'filters[date][from]': (0, _utils.getDateString)(-1),
            'filters[date][to]': (0, _utils.getDateString)(),
            sort_direction: 'desc'
          }
        });

        // Manual fetches (e.g. page load, user pagination) should update the view immediately,
        // while polls are stored in-state until the user manually triggers the 'Refresh' action
        if (isPoll) {
          actions.onPollInterval(response);
        } else {
          actions.updateView(response);
        }
      } catch (e) {
        if (isPoll) {
          // If polling fails, it will typically be due to http connection -
          // we should send a more human-readable message if so
          (0, _flash_messages.flashErrorToast)(_constants2.POLLING_ERROR_TITLE, {
            text: _constants2.POLLING_ERROR_TEXT,
            toastLifeTimeMs: _constants2.POLLING_DURATION * 0.75
          });
        } else {
          (0, _flash_messages.flashAPIErrors)(e);
        }
      }
    },
    onPollInterval: (data, breakpoint) => {
      breakpoint(); // Prevents errors if logic unmounts while fetching

      const previousResults = values.meta.page.total_results;
      const newResults = data.meta.page.total_results;
      const isEmpty = previousResults === 0;
      const hasNewData = previousResults !== newResults;
      if (isEmpty && hasNewData) {
        actions.updateView(data); // Empty logs should automatically update with new data without a manual action
      } else if (hasNewData) {
        actions.storePolledData(data); // Otherwise, store any new data until the user manually refreshes the table
      }
    },

    onUserRefresh: () => {
      actions.updateView(values.polledData);
    }
  }),
  events: ({
    values
  }) => ({
    beforeUnmount() {
      if (values.intervalId !== null) clearInterval(values.intervalId);
    }
  })
});
exports.ApiLogsLogic = ApiLogsLogic;