"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CrawlerLogic = void 0;
var _kea = require("kea");
var _flash_messages = require("../../../shared/flash_messages");
var _http = require("../../../shared/http");
var _engine = require("../engine");
var _crawler_domains_logic = require("./crawler_domains_logic");
var _types = require("./types");
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 POLLING_DURATION = 1000;
const POLLING_DURATION_ON_FAILURE = 5000;
const ACTIVE_STATUSES = [_types.CrawlerStatus.Pending, _types.CrawlerStatus.Starting, _types.CrawlerStatus.Running, _types.CrawlerStatus.Canceling];
const CrawlerLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'app_search', 'crawler_logic'],
  actions: {
    clearTimeoutId: true,
    createNewTimeoutForCrawlerData: duration => ({
      duration
    }),
    fetchCrawlerData: true,
    onCreateNewTimeout: timeoutId => ({
      timeoutId
    }),
    onReceiveCrawlerData: data => ({
      data
    }),
    onStartCrawlRequestComplete: true,
    startCrawl: overrides => ({
      overrides
    }),
    stopCrawl: () => null
  },
  reducers: {
    dataLoading: [true, {
      onReceiveCrawlerData: () => false
    }],
    domains: [[], {
      onReceiveCrawlerData: (_, {
        data: {
          domains
        }
      }) => domains
    }],
    events: [[], {
      onReceiveCrawlerData: (_, {
        data: {
          events
        }
      }) => events
    }],
    mostRecentCrawlRequest: [null, {
      onReceiveCrawlerData: (_, {
        data: {
          mostRecentCrawlRequest
        }
      }) => mostRecentCrawlRequest
    }],
    timeoutId: [null, {
      clearTimeoutId: () => null,
      onCreateNewTimeout: (_, {
        timeoutId
      }) => timeoutId
    }]
  },
  selectors: ({
    selectors
  }) => ({
    mostRecentCrawlRequestStatus: [() => [selectors.mostRecentCrawlRequest], crawlRequest => {
      if (crawlRequest) {
        return crawlRequest.status;
      }
      return _types.CrawlerStatus.Success;
    }]
  }),
  listeners: ({
    actions,
    values
  }) => ({
    fetchCrawlerData: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      try {
        const response = await http.get(`/internal/app_search/engines/${engineName}/crawler`);
        const crawlerData = (0, _utils.crawlerDataServerToClient)(response);
        actions.onReceiveCrawlerData(crawlerData);
        const continuePoll = crawlerData.mostRecentCrawlRequest && ACTIVE_STATUSES.includes(crawlerData.mostRecentCrawlRequest.status) || crawlerData.events.find(event => ACTIVE_STATUSES.includes(event.status));
        if (continuePoll) {
          actions.createNewTimeoutForCrawlerData(POLLING_DURATION);
        } else {
          actions.clearTimeoutId();
        }
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
        actions.createNewTimeoutForCrawlerData(POLLING_DURATION_ON_FAILURE);
      }
    },
    startCrawl: async ({
      overrides = {}
    }) => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      try {
        await http.post(`/internal/app_search/engines/${engineName}/crawler/crawl_requests`, {
          body: JSON.stringify({
            overrides
          })
        });
        actions.fetchCrawlerData();
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      } finally {
        actions.onStartCrawlRequestComplete();
      }
    },
    stopCrawl: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      try {
        await http.post(`/internal/app_search/engines/${engineName}/crawler/crawl_requests/cancel`);
        actions.fetchCrawlerData();
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    },
    createNewTimeoutForCrawlerData: ({
      duration
    }) => {
      if (values.timeoutId) {
        clearTimeout(values.timeoutId);
      }
      const timeoutIdId = setTimeout(() => {
        actions.fetchCrawlerData();
      }, duration);
      actions.onCreateNewTimeout(timeoutIdId);
    },
    [_crawler_domains_logic.CrawlerDomainsLogic.actionTypes.crawlerDomainDeleted]: ({
      data
    }) => {
      actions.onReceiveCrawlerData(data);
    }
  }),
  events: ({
    values
  }) => ({
    beforeUnmount: () => {
      if (values.timeoutId) {
        clearTimeout(values.timeoutId);
      }
    }
  })
});
exports.CrawlerLogic = CrawlerLogic;