"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MetaEngineCreationLogic = void 0;
var _reactRouterDom = require("react-router-dom");
var _kea = require("kea");
var _constants = require("../../../shared/constants");
var _flash_messages = require("../../../shared/flash_messages");
var _http = require("../../../shared/http");
var _kibana = require("../../../shared/kibana");
var _routes = require("../../routes");
var _format_api_name = require("../../utils/format_api_name");
var _constants2 = require("./constants");
/*
 * 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 MetaEngineCreationLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'app_search', 'meta_engine_creation_logic'],
  actions: {
    fetchIndexedEngineNames: (page = _constants.DEFAULT_META.page.current) => ({
      page
    }),
    onEngineCreationSuccess: true,
    setIndexedEngineNames: indexedEngineNames => ({
      indexedEngineNames
    }),
    setRawName: rawName => ({
      rawName
    }),
    setSelectedIndexedEngineNames: selectedIndexedEngineNames => ({
      selectedIndexedEngineNames
    }),
    submitEngine: true,
    onSubmitError: true
  },
  reducers: {
    isLoading: [false, {
      submitEngine: () => true,
      onSubmitError: () => false
    }],
    indexedEngineNames: [[], {
      setIndexedEngineNames: (_, {
        indexedEngineNames
      }) => indexedEngineNames
    }],
    rawName: ['', {
      setRawName: (_, {
        rawName
      }) => rawName
    }],
    selectedIndexedEngineNames: [[], {
      setSelectedIndexedEngineNames: (_, {
        selectedIndexedEngineNames
      }) => selectedIndexedEngineNames
    }]
  },
  selectors: ({
    selectors
  }) => ({
    name: [() => [selectors.rawName], rawName => (0, _format_api_name.formatApiName)(rawName)]
  }),
  listeners: ({
    values,
    actions
  }) => ({
    fetchIndexedEngineNames: async ({
      page
    }) => {
      const {
        http
      } = _http.HttpLogic.values;
      let response;
      try {
        response = await http.get('/internal/app_search/engines', {
          query: {
            type: 'indexed',
            'page[current]': page,
            'page[size]': _constants.DEFAULT_META.page.size
          }
        });
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
      if (response) {
        const engineNames = response.results.map(result => result.name);
        actions.setIndexedEngineNames([...values.indexedEngineNames, ...engineNames]);
        if (page < response.meta.page.total_pages) {
          actions.fetchIndexedEngineNames(page + 1);
        }
      }
    },
    onEngineCreationSuccess: () => {
      const {
        name
      } = values;
      const {
        navigateToUrl
      } = _kibana.KibanaLogic.values;
      const enginePath = (0, _reactRouterDom.generatePath)(_routes.ENGINE_PATH, {
        engineName: name
      });
      (0, _flash_messages.flashSuccessToast)((0, _constants2.META_ENGINE_CREATION_SUCCESS_MESSAGE)(name));
      navigateToUrl(enginePath);
    },
    submitEngine: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      const {
        name,
        selectedIndexedEngineNames
      } = values;
      const body = JSON.stringify({
        name,
        type: 'meta',
        source_engines: selectedIndexedEngineNames
      });
      try {
        await http.post('/internal/app_search/engines', {
          body
        });
        actions.onEngineCreationSuccess();
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
        actions.onSubmitError();
      }
    }
  })
});
exports.MetaEngineCreationLogic = MetaEngineCreationLogic;