"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CreateSearchApplicationLogic = void 0;
var _kea = require("kea");
var _api = require("../../../../../common/types/api");
var _kibana = require("../../../shared/kibana");
var _create_search_application_api_logic = require("../../api/search_applications/create_search_application_api_logic");
var _routes = require("../../routes");
var _search_applications_list_logic = require("./search_applications_list_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 CreateSearchApplicationLogic = (0, _kea.kea)({
  actions: {
    createSearchApplication: true,
    setName: name => ({
      name
    }),
    setSelectedIndices: indices => ({
      indices
    })
  },
  connect: {
    actions: [_search_applications_list_logic.SearchApplicationsListLogic, ['fetchSearchApplications'], _create_search_application_api_logic.CreateSearchApplicationApiLogic, ['makeRequest as createSearchApplicationRequest', 'apiSuccess as searchApplicationCreated', 'apiError as searchApplicationCreateError']],
    values: [_create_search_application_api_logic.CreateSearchApplicationApiLogic, ['status as createSearchApplicationStatus', 'error as createSearchApplicationError']]
  },
  listeners: ({
    actions,
    values
  }) => ({
    createSearchApplication: () => {
      actions.createSearchApplicationRequest({
        indices: values.selectedIndices,
        name: values.searchApplicationName
      });
    },
    searchApplicationCreated: () => {
      actions.fetchSearchApplications();
      _kibana.KibanaLogic.values.navigateToUrl(_routes.SEARCH_APPLICATIONS_PATH);
    }
  }),
  path: ['enterprise_search', 'content', 'create_search_application_logic'],
  reducers: {
    searchApplicationName: ['', {
      setName: (_, {
        name
      }) => name
    }],
    selectedIndices: [[], {
      setSelectedIndices: (_, {
        indices
      }) => indices
    }]
  },
  selectors: ({
    selectors
  }) => ({
    createDisabled: [() => [selectors.indicesStatus, selectors.searchApplicationNameStatus], (indicesStatus, searchApplicationNameStatus) => indicesStatus !== 'complete' || searchApplicationNameStatus !== 'complete'],
    searchApplicationNameStatus: [() => [selectors.searchApplicationName], searchApplicationName => {
      if (searchApplicationName.length === 0) return 'incomplete';
      return 'complete';
    }],
    formDisabled: [() => [selectors.createSearchApplicationStatus], createSearchApplicationStatus => createSearchApplicationStatus === _api.Status.LOADING],
    indicesStatus: [() => [selectors.selectedIndices], selectedIndices => selectedIndices.length > 0 ? 'complete' : 'incomplete']
  })
});
exports.CreateSearchApplicationLogic = CreateSearchApplicationLogic;