"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.defaultSearchResultConfig = exports.DisplaySettingsLogic = void 0;
var _kea = require("kea");
var _lodash = require("lodash");
var _flash_messages = require("../../../../../shared/flash_messages");
var _http = require("../../../../../shared/http");
var _kibana = require("../../../../../shared/kibana");
var _app_logic = require("../../../../app_logic");
var _routes = require("../../../../routes");
var _source_logic = require("../../source_logic");
var _constants = 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 defaultSearchResultConfig = {
  titleField: '',
  subtitleField: '',
  descriptionField: '',
  urlField: '',
  typeField: '',
  mediaTypeField: '',
  createdByField: '',
  updatedByField: '',
  color: '#000000',
  detailFields: []
};
exports.defaultSearchResultConfig = defaultSearchResultConfig;
const DisplaySettingsLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'workplace_search', 'display_settings_logic'],
  actions: {
    onInitializeDisplaySettings: displaySettingsProps => displaySettingsProps,
    setServerResponseData: displaySettingsProps => displaySettingsProps,
    setTitleField: titleField => titleField,
    setUrlField: urlField => urlField,
    setSubtitleField: subtitleField => subtitleField,
    setDescriptionField: descriptionField => descriptionField,
    setTypeField: typeField => typeField,
    setMediaTypeField: mediaTypeField => mediaTypeField,
    setCreatedByField: createdByField => createdByField,
    setUpdatedByField: updatedByField => updatedByField,
    setColorField: hex => hex,
    setDetailFields: result => ({
      result
    }),
    openEditDetailField: editFieldIndex => editFieldIndex,
    removeDetailField: index => index,
    setNavigatingBetweenTabs: navigatingBetweenTabs => navigatingBetweenTabs,
    handleSelectedTabChanged: tabId => tabId,
    addDetailField: newField => newField,
    updateDetailField: (updatedField, index) => ({
      updatedField,
      index
    }),
    toggleFieldEditorModal: () => true,
    toggleTitleFieldHover: () => true,
    toggleSubtitleFieldHover: () => true,
    toggleDescriptionFieldHover: () => true,
    toggleTypeFieldHover: () => true,
    toggleMediaTypeFieldHover: () => true,
    toggleCreatedByFieldHover: () => true,
    toggleUpdatedByFieldHover: () => true,
    toggleUrlFieldHover: () => true,
    initializeDisplaySettings: () => true,
    setServerData: () => true
  },
  reducers: {
    sourceName: ['', {
      onInitializeDisplaySettings: (_, {
        sourceName
      }) => sourceName
    }],
    sourceId: ['', {
      onInitializeDisplaySettings: (_, {
        sourceId
      }) => sourceId
    }],
    schemaFields: [{}, {
      onInitializeDisplaySettings: (_, {
        schemaFields
      }) => schemaFields
    }],
    exampleDocuments: [[], {
      onInitializeDisplaySettings: (_, {
        exampleDocuments
      }) => exampleDocuments
    }],
    serverSearchResultConfig: [defaultSearchResultConfig, {
      onInitializeDisplaySettings: (_, {
        searchResultConfig
      }) => setDefaultColor(searchResultConfig),
      setServerResponseData: (_, {
        searchResultConfig
      }) => searchResultConfig
    }],
    searchResultConfig: [defaultSearchResultConfig, {
      onInitializeDisplaySettings: (_, {
        searchResultConfig
      }) => setDefaultColor(searchResultConfig),
      setServerResponseData: (_, {
        searchResultConfig
      }) => searchResultConfig,
      setTitleField: (searchResultConfig, titleField) => ({
        ...searchResultConfig,
        titleField
      }),
      setSubtitleField: (searchResultConfig, subtitleField) => ({
        ...searchResultConfig,
        subtitleField
      }),
      setUrlField: (searchResultConfig, urlField) => ({
        ...searchResultConfig,
        urlField
      }),
      setDescriptionField: (searchResultConfig, descriptionField) => ({
        ...searchResultConfig,
        descriptionField
      }),
      setTypeField: (searchResultConfig, typeField) => ({
        ...searchResultConfig,
        typeField
      }),
      setMediaTypeField: (searchResultConfig, mediaTypeField) => ({
        ...searchResultConfig,
        mediaTypeField
      }),
      setCreatedByField: (searchResultConfig, createdByField) => ({
        ...searchResultConfig,
        createdByField
      }),
      setUpdatedByField: (searchResultConfig, updatedByField) => ({
        ...searchResultConfig,
        updatedByField
      }),
      setColorField: (searchResultConfig, color) => ({
        ...searchResultConfig,
        color
      }),
      setDetailFields: (searchResultConfig, {
        result: {
          destination,
          source
        }
      }) => {
        const detailFields = (0, _lodash.cloneDeep)(searchResultConfig.detailFields);
        const element = detailFields[source.index];
        detailFields.splice(source.index, 1);
        detailFields.splice(destination.index, 0, element);
        return {
          ...searchResultConfig,
          detailFields
        };
      },
      addDetailField: (searchResultConfig, newfield) => {
        const detailFields = (0, _lodash.cloneDeep)(searchResultConfig.detailFields);
        detailFields.push(newfield);
        return {
          ...searchResultConfig,
          detailFields
        };
      },
      removeDetailField: (searchResultConfig, index) => {
        const detailFields = (0, _lodash.cloneDeep)(searchResultConfig.detailFields);
        detailFields.splice(index, 1);
        return {
          ...searchResultConfig,
          detailFields
        };
      },
      updateDetailField: (searchResultConfig, {
        updatedField,
        index
      }) => {
        const detailFields = (0, _lodash.cloneDeep)(searchResultConfig.detailFields);
        detailFields[index] = updatedField;
        return {
          ...searchResultConfig,
          detailFields
        };
      }
    }],
    serverRoute: ['', {
      onInitializeDisplaySettings: (_, {
        serverRoute
      }) => serverRoute
    }],
    editFieldIndex: [null, {
      openEditDetailField: (_, openEditDetailField) => openEditDetailField,
      toggleFieldEditorModal: () => null
    }],
    dataLoading: [true, {
      onInitializeDisplaySettings: () => false
    }],
    navigatingBetweenTabs: [false, {
      setNavigatingBetweenTabs: (_, navigatingBetweenTabs) => navigatingBetweenTabs
    }],
    addFieldModalVisible: [false, {
      toggleFieldEditorModal: addFieldModalVisible => !addFieldModalVisible,
      openEditDetailField: () => true,
      updateDetailField: () => false,
      addDetailField: () => false
    }],
    titleFieldHover: [false, {
      toggleTitleFieldHover: titleFieldHover => !titleFieldHover
    }],
    urlFieldHover: [false, {
      toggleUrlFieldHover: urlFieldHover => !urlFieldHover
    }],
    subtitleFieldHover: [false, {
      toggleSubtitleFieldHover: subtitleFieldHover => !subtitleFieldHover
    }],
    descriptionFieldHover: [false, {
      toggleDescriptionFieldHover: descriptionFieldHover => !descriptionFieldHover
    }],
    typeFieldHover: [false, {
      toggleTypeFieldHover: typeFieldHover => !typeFieldHover
    }],
    mediaTypeFieldHover: [false, {
      toggleMediaTypeFieldHover: mediaTypeFieldHover => !mediaTypeFieldHover
    }],
    createdByFieldHover: [false, {
      toggleCreatedByFieldHover: createdByFieldHover => !createdByFieldHover
    }],
    updatedByFieldHover: [false, {
      toggleUpdatedByFieldHover: updatedByFieldHover => !updatedByFieldHover
    }]
  },
  selectors: ({
    selectors
  }) => ({
    fieldOptions: [() => [selectors.schemaFields], schemaFields => Object.keys(schemaFields).map(euiSelectObjectFromValue)],
    optionalFieldOptions: [() => [selectors.fieldOptions], fieldOptions => {
      const optionalFieldOptions = (0, _lodash.cloneDeep)(fieldOptions);
      optionalFieldOptions.unshift({
        value: _constants.LEAVE_UNASSIGNED_FIELD,
        text: _constants.LEAVE_UNASSIGNED_FIELD
      });
      return optionalFieldOptions;
    }],
    // We don't want to let the user add a duplicate detailField.
    availableFieldOptions: [() => [selectors.fieldOptions, selectors.searchResultConfig], (fieldOptions, {
      detailFields
    }) => {
      const usedFields = detailFields.map(usedField => euiSelectObjectFromValue(usedField.fieldName));
      return (0, _lodash.differenceBy)(fieldOptions, usedFields, 'value');
    }],
    unsavedChanges: [() => [selectors.searchResultConfig, selectors.serverSearchResultConfig], (uiConfig, serverConfig) => !(0, _lodash.isEqual)(uiConfig, serverConfig)]
  }),
  listeners: ({
    actions,
    values
  }) => ({
    initializeDisplaySettings: async () => {
      const {
        isOrganization
      } = _app_logic.AppLogic.values;
      const {
        contentSource: {
          id: sourceId
        }
      } = _source_logic.SourceLogic.values;
      const route = isOrganization ? `/internal/workplace_search/org/sources/${sourceId}/display_settings/config` : `/internal/workplace_search/account/sources/${sourceId}/display_settings/config`;
      try {
        const response = await _http.HttpLogic.values.http.get(route);
        actions.onInitializeDisplaySettings({
          // isOrganization is not typed
          // @ts-expect-error TS2345
          isOrganization,
          sourceId,
          serverRoute: route,
          ...response
        });
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    },
    setServerData: async () => {
      const {
        searchResultConfig,
        serverRoute
      } = values;
      try {
        const response = await _http.HttpLogic.values.http.post(serverRoute, {
          body: JSON.stringify({
            ...searchResultConfig
          })
        });
        actions.setServerResponseData(response);
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    },
    setServerResponseData: () => {
      (0, _flash_messages.flashSuccessToast)(_constants.SUCCESS_MESSAGE);
    },
    toggleFieldEditorModal: () => {
      (0, _flash_messages.clearFlashMessages)();
    },
    handleSelectedTabChanged: async (tabId, breakpoint) => {
      const {
        isOrganization
      } = _app_logic.AppLogic.values;
      const {
        sourceId
      } = values;
      const path = tabId === 'result_detail' ? (0, _routes.getContentSourcePath)(_routes.DISPLAY_SETTINGS_RESULT_DETAIL_PATH, sourceId, isOrganization) : (0, _routes.getContentSourcePath)(_routes.DISPLAY_SETTINGS_SEARCH_RESULT_PATH, sourceId, isOrganization);

      // This method is needed because the shared `UnsavedChangesPrompt` component is triggered
      // when navigating between tabs. We set a boolean flag that tells the prompt there are no
      // unsaved changes when navigating between the tabs and reset it one the transition is complete
      // in order to restore the intended functionality when navigating away with unsaved changes.
      actions.setNavigatingBetweenTabs(true);
      await breakpoint();
      _kibana.KibanaLogic.values.navigateToUrl(path);
      actions.setNavigatingBetweenTabs(false);
    }
  })
});
exports.DisplaySettingsLogic = DisplaySettingsLogic;
const euiSelectObjectFromValue = value => ({
  text: value,
  value
});

// By default, the color is `null` on the server. The color is a required field and the
// EuiColorPicker components doesn't allow the field to be required so the form can be
// submitted with no color and this results in a server error. The default should be black
// and this allows the `searchResultConfig` and the `serverSearchResultConfig` reducers to
// stay synced on initialization.
const setDefaultColor = searchResultConfig => ({
  ...searchResultConfig,
  color: searchResultConfig.color || '#000000'
});