"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AutomaticCrawlSchedulerLogic = void 0;
var _kea = require("kea");
var _i18n = require("@kbn/i18n");
var _flash_messages = require("../../../../../shared/flash_messages");
var _http = require("../../../../../shared/http");
var _engine = require("../../../engine");
var _types = require("../../types");
var _manage_crawls_popover_logic = require("./manage_crawls_popover_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 DEFAULT_VALUES = {
  crawlFrequency: 7,
  crawlUnit: _types.CrawlUnits.days
};
const AutomaticCrawlSchedulerLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'app_search', 'crawler', 'automatic_crawl_scheduler'],
  actions: () => ({
    clearCrawlSchedule: true,
    deleteCrawlSchedule: true,
    disableCrawlAutomatically: true,
    onDoneSubmitting: true,
    enableCrawlAutomatically: true,
    fetchCrawlSchedule: true,
    saveChanges: true,
    setCrawlSchedule: crawlSchedule => ({
      crawlSchedule
    }),
    submitCrawlSchedule: true,
    setCrawlFrequency: crawlFrequency => ({
      crawlFrequency
    }),
    setCrawlUnit: crawlUnit => ({
      crawlUnit
    }),
    toggleCrawlAutomatically: true
  }),
  reducers: () => ({
    crawlAutomatically: [false, {
      clearCrawlSchedule: () => false,
      setCrawlSchedule: () => true,
      toggleCrawlAutomatically: crawlAutomatically => !crawlAutomatically
    }],
    crawlFrequency: [DEFAULT_VALUES.crawlFrequency, {
      clearCrawlSchedule: () => DEFAULT_VALUES.crawlFrequency,
      setCrawlSchedule: (_, {
        crawlSchedule: {
          frequency
        }
      }) => frequency,
      setCrawlFrequency: (_, {
        crawlFrequency
      }) => crawlFrequency
    }],
    crawlUnit: [DEFAULT_VALUES.crawlUnit, {
      clearCrawlSchedule: () => DEFAULT_VALUES.crawlUnit,
      setCrawlSchedule: (_, {
        crawlSchedule: {
          unit
        }
      }) => unit,
      setCrawlUnit: (_, {
        crawlUnit
      }) => crawlUnit
    }],
    isSubmitting: [false, {
      deleteCrawlSchedule: () => true,
      onDoneSubmitting: () => false,
      submitCrawlSchedule: () => true
    }]
  }),
  listeners: ({
    actions,
    values
  }) => ({
    deleteCrawlSchedule: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      const {
        closePopover
      } = _manage_crawls_popover_logic.ManageCrawlsPopoverLogic.actions;
      try {
        await http.delete(`/internal/app_search/engines/${engineName}/crawler/crawl_schedule`);
        actions.clearCrawlSchedule();
        (0, _flash_messages.flashSuccessToast)(_i18n.i18n.translate('xpack.enterpriseSearch.appSearch.crawler.automaticCrawlScheduler.disableCrawlSchedule.successMessage', {
          defaultMessage: 'Automatic crawling has been disabled.'
        }));
        closePopover();
      } catch (e) {
        var _e$response;
        // A 404 is expected and means the user has no crawl schedule to delete
        if (((_e$response = e.response) === null || _e$response === void 0 ? void 0 : _e$response.status) === 404) {
          actions.clearCrawlSchedule();
          closePopover();
        } else {
          (0, _flash_messages.flashAPIErrors)(e);
          // Keep the popover open
        }
      } finally {
        actions.onDoneSubmitting();
      }
    },
    fetchCrawlSchedule: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      try {
        const crawlSchedule = await http.get(`/internal/app_search/engines/${engineName}/crawler/crawl_schedule`);
        actions.setCrawlSchedule(crawlSchedule);
      } catch (e) {
        // A 404 is expected and means the user does not have crawl schedule
        // for this engine. We continue to use the defaults.
        if (e.response.status === 404) {
          actions.clearCrawlSchedule();
        } else {
          (0, _flash_messages.flashAPIErrors)(e);
        }
      }
    },
    saveChanges: () => {
      if (values.crawlAutomatically) {
        actions.submitCrawlSchedule();
      } else {
        actions.deleteCrawlSchedule();
      }
    },
    submitCrawlSchedule: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        engineName
      } = _engine.EngineLogic.values;
      const {
        closePopover
      } = _manage_crawls_popover_logic.ManageCrawlsPopoverLogic.actions;
      try {
        const crawlSchedule = await http.put(`/internal/app_search/engines/${engineName}/crawler/crawl_schedule`, {
          body: JSON.stringify({
            unit: values.crawlUnit,
            frequency: values.crawlFrequency
          })
        });
        actions.setCrawlSchedule(crawlSchedule);
        (0, _flash_messages.flashSuccessToast)(_i18n.i18n.translate('xpack.enterpriseSearch.appSearch.crawler.automaticCrawlScheduler.submitCrawlSchedule.successMessage', {
          defaultMessage: 'Your automatic crawling schedule has been updated.'
        }));
        closePopover();
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      } finally {
        actions.onDoneSubmitting();
      }
    }
  })
});
exports.AutomaticCrawlSchedulerLogic = AutomaticCrawlSchedulerLogic;