"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CrawlerLogic = void 0;
var _kea = require("kea");
var _i18n = require("@kbn/i18n");
var _flash_messages = require("../../../../shared/flash_messages");
var _http = require("../../../../shared/http");
var _start_sync_api_logic = require("../../../api/connector/start_sync_api_logic");
var _get_crawler_api_logic = require("../../../api/crawler/get_crawler_api_logic");
var _cached_fetch_index_api_logic = require("../../../api/index/cached_fetch_index_api_logic");
var _indices = require("../../../utils/indices");
var _index_name_logic = require("../index_name_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 CrawlerLogic = (0, _kea.kea)({
  actions: {
    fetchCrawlerData: true,
    reApplyCrawlRules: domain => ({
      domain
    }),
    startCrawl: overrides => ({
      overrides
    }),
    stopCrawl: () => null
  },
  connect: {
    actions: [_get_crawler_api_logic.GetCrawlerApiLogic, ['apiError', 'apiSuccess'], _start_sync_api_logic.StartSyncApiLogic, ['makeRequest as makeStartSyncRequest'], _cached_fetch_index_api_logic.CachedFetchIndexApiLogic, ['makeRequest as makeFetchIndexRequest']],
    values: [_get_crawler_api_logic.GetCrawlerApiLogic, ['status', 'data'], _cached_fetch_index_api_logic.CachedFetchIndexApiLogic, ['indexData']]
  },
  listeners: ({
    actions,
    values
  }) => ({
    fetchCrawlerData: () => {
      const {
        indexName
      } = _index_name_logic.IndexNameLogic.values;
      _get_crawler_api_logic.GetCrawlerApiLogic.actions.makeRequest({
        indexName
      });
    },
    reApplyCrawlRules: async ({
      domain
    }) => {
      const {
        indexName
      } = _index_name_logic.IndexNameLogic.values;
      const {
        http
      } = _http.HttpLogic.values;
      const requestBody = {};
      if (domain) {
        requestBody.domains = [domain.url];
      }
      try {
        await http.post(`/internal/enterprise_search/indices/${indexName}/crawler/process_crawls`, {
          body: JSON.stringify(requestBody)
        });
        (0, _flash_messages.flashSuccessToast)(_i18n.i18n.translate('xpack.enterpriseSearch.crawler.manageCrawlsPopover.reApplyCrawlRules.successMessage', {
          defaultMessage: 'Crawl rules are being re-applied in the background'
        }));
        CrawlerLogic.actions.fetchCrawlerData();
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    },
    startCrawl: async ({
      overrides = {}
    }) => {
      try {
        if ((0, _indices.isCrawlerIndex)(values.indexData) && values.indexData.connector) {
          actions.makeStartSyncRequest({
            connectorId: values.indexData.connector.id,
            nextSyncConfig: overrides
          });
          actions.fetchCrawlerData();
        }
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    },
    stopCrawl: async () => {
      const {
        indexName
      } = _index_name_logic.IndexNameLogic.values;
      const {
        http
      } = _http.HttpLogic.values;
      try {
        await http.post(`/internal/enterprise_search/indices/${indexName}/crawler/crawl_requests/cancel`);
        actions.fetchCrawlerData();
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    }
  }),
  path: ['enterprise_search', 'crawler_logic'],
  reducers: {
    dataLoading: [true, {
      apiError: () => false,
      apiSuccess: () => false
    }]
  },
  selectors: ({
    selectors
  }) => ({
    domains: [() => [selectors.data], data => {
      var _data$domains;
      return (_data$domains = data === null || data === void 0 ? void 0 : data.domains) !== null && _data$domains !== void 0 ? _data$domains : [];
    }],
    events: [() => [selectors.data], data => {
      var _data$events;
      return (_data$events = data === null || data === void 0 ? void 0 : data.events) !== null && _data$events !== void 0 ? _data$events : [];
    }],
    mostRecentCrawlRequest: [() => [selectors.data], data => {
      var _data$mostRecentCrawl;
      return (_data$mostRecentCrawl = data === null || data === void 0 ? void 0 : data.mostRecentCrawlRequest) !== null && _data$mostRecentCrawl !== void 0 ? _data$mostRecentCrawl : null;
    }],
    mostRecentCrawlRequestStatus: [() => [selectors.mostRecentCrawlRequest], crawlRequest => {
      var _crawlRequest$status;
      return (_crawlRequest$status = crawlRequest === null || crawlRequest === void 0 ? void 0 : crawlRequest.status) !== null && _crawlRequest$status !== void 0 ? _crawlRequest$status : null;
    }]
  })
});
exports.CrawlerLogic = CrawlerLogic;