"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ConnectorConfigurationLogic = void 0;
var _kea = require("kea");
var _searchConnectors = require("@kbn/search-connectors");
var _is_category_entry = require("../../../../../../common/connectors/is_category_entry");
var _is_not_nullish = require("../../../../../../common/utils/is_not_nullish");
var _update_connector_configuration_api_logic = require("../../../api/connector/update_connector_configuration_api_logic");
var _cached_fetch_index_api_logic = require("../../../api/index/cached_fetch_index_api_logic");
var _indices = require("../../../utils/indices");
var _connector_configuration_utils = require("./utils/connector_configuration_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 ConnectorConfigurationLogic = (0, _kea.kea)({
  actions: {
    saveConfig: true,
    setConfigState: configState => ({
      configState
    }),
    setIsEditing: isEditing => ({
      isEditing
    }),
    setLocalConfigEntry: configEntry => ({
      ...configEntry
    }),
    setLocalConfigState: configState => ({
      configState
    }),
    setShouldStartInEditMode: shouldStartInEditMode => ({
      shouldStartInEditMode
    })
  },
  connect: {
    actions: [_update_connector_configuration_api_logic.ConnectorConfigurationApiLogic, ['apiSuccess', 'makeRequest'], _cached_fetch_index_api_logic.CachedFetchIndexApiLogic, ['apiSuccess as fetchIndexApiSuccess']],
    values: [_cached_fetch_index_api_logic.CachedFetchIndexApiLogic, ['indexData as index']]
  },
  events: ({
    actions,
    values
  }) => ({
    afterMount: () => {
      actions.setConfigState((0, _indices.isConnectorIndex)(values.index) ? values.index.connector.configuration : {});
      if ((0, _indices.isConnectorIndex)(values.index) && (values.index.connector.status === _searchConnectors.ConnectorStatus.CREATED || values.index.connector.status === _searchConnectors.ConnectorStatus.NEEDS_CONFIGURATION)) {
        // Only start in edit mode if we haven't configured yet
        // Necessary to prevent a race condition between saving config and getting updated connector
        actions.setShouldStartInEditMode(true);
      }
    }
  }),
  listeners: ({
    actions,
    values
  }) => ({
    apiSuccess: ({
      indexName
    }) => {
      _cached_fetch_index_api_logic.CachedFetchIndexApiLogic.actions.makeRequest({
        indexName
      });
    },
    fetchIndexApiSuccess: index => {
      if (!values.isEditing && (0, _indices.isConnectorIndex)(index)) {
        actions.setConfigState(index.connector.configuration);
      }
      if (!values.isEditing && values.shouldStartInEditMode && (0, _indices.isConnectorIndex)(index) && index.connector.status === _searchConnectors.ConnectorStatus.NEEDS_CONFIGURATION && index.connector.configuration && Object.entries(index.connector.configuration).length > 0) {
        actions.setIsEditing(true);
      }
    },
    saveConfig: () => {
      if ((0, _indices.isConnectorIndex)(values.index)) {
        var _values$index$connect;
        actions.makeRequest({
          configuration: Object.keys(values.localConfigState).map(key => {
            var _entry$value;
            const entry = values.localConfigState[key];
            if ((0, _is_category_entry.isCategoryEntry)(entry) || !entry) {
              return null;
            }
            return {
              key,
              value: (_entry$value = entry.value) !== null && _entry$value !== void 0 ? _entry$value : ''
            };
          }).filter(_is_not_nullish.isNotNullish).reduce((prev, {
            key,
            value
          }) => {
            prev[key] = value;
            return prev;
          }, {}),
          connectorId: values.index.connector.id,
          indexName: (_values$index$connect = values.index.connector.index_name) !== null && _values$index$connect !== void 0 ? _values$index$connect : ''
        });
      }
    },
    setIsEditing: isEditing => {
      if (isEditing) {
        actions.setLocalConfigState(values.configState);
      }
    }
  }),
  path: ['enterprise_search', 'content', 'connector_configuration'],
  reducers: () => ({
    configState: [{}, {
      apiSuccess: (_, {
        configuration
      }) => configuration,
      setConfigState: (_, {
        configState
      }) => configState
    }],
    isEditing: [false, {
      apiSuccess: () => false,
      setIsEditing: (_, {
        isEditing
      }) => isEditing
    }],
    localConfigState: [{}, {
      setLocalConfigEntry: (configState, {
        key,
        display,
        type,
        validations,
        value,
        ...configEntry
      }) => ({
        ...configState,
        [key]: {
          ...configEntry,
          display,
          type,
          validations: validations !== null && validations !== void 0 ? validations : [],
          value: display ? (0, _connector_configuration_utils.ensureCorrectTyping)(type, value) : value // only check type if field had a specified eui element
        }
      }),

      setLocalConfigState: (_, {
        configState
      }) => configState
    }],
    shouldStartInEditMode: [false, {
      apiSuccess: () => false,
      setShouldStartInEditMode: (_, {
        shouldStartInEditMode
      }) => shouldStartInEditMode
    }]
  }),
  selectors: ({
    selectors
  }) => ({
    configView: [() => [selectors.configState, selectors.index], (configState, index) => (0, _connector_configuration_utils.sortAndFilterConnectorConfiguration)(configState, (0, _indices.isConnectorIndex)(index) ? index.connector.is_native : false)],
    localConfigView: [() => [selectors.localConfigState, selectors.index], (configState, index) => (0, _connector_configuration_utils.sortAndFilterConnectorConfiguration)(configState, (0, _indices.isConnectorIndex)(index) ? index.connector.is_native : false)]
  })
});
exports.ConnectorConfigurationLogic = ConnectorConfigurationLogic;