"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IndexPipelinesConfigurationsLogic = void 0;
var _kea = require("kea");
var _fetch_custom_pipeline_api_logic = require("../../../api/index/fetch_custom_pipeline_api_logic");
var _index_name_logic = require("../index_name_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 IndexPipelinesConfigurationsLogic = (0, _kea.kea)({
  actions: {
    selectPipeline: pipeline => ({
      pipeline
    })
  },
  connect: {
    actions: [_fetch_custom_pipeline_api_logic.FetchCustomPipelineApiLogic, ['apiSuccess as fetchIndexPipelinesDataSuccess']],
    values: [_index_name_logic.IndexNameLogic, ['indexName'], _fetch_custom_pipeline_api_logic.FetchCustomPipelineApiLogic, ['data as indexPipelinesData']]
  },
  events: ({
    actions,
    values
  }) => ({
    afterMount: () => {
      if (!values.indexPipelinesData || values.indexPipelinesData.length === 0) {
        return;
      }
      const pipelineNames = Object.keys(values.indexPipelinesData).sort();
      const defaultPipeline = pipelineNames.includes(values.indexName) ? values.indexName : pipelineNames[0];
      actions.selectPipeline(defaultPipeline);
    }
  }),
  listeners: ({
    actions,
    values
  }) => ({
    fetchIndexPipelinesDataSuccess: pipelines => {
      const names = Object.keys(pipelines !== null && pipelines !== void 0 ? pipelines : {}).sort();
      if (names.length > 0 && values.selectedPipelineId.length === 0) {
        const defaultPipeline = names.includes(values.indexName) ? values.indexName : names[0];
        actions.selectPipeline(defaultPipeline);
      }
    }
  }),
  path: ['enterprise_search', 'content', 'pipelines_json_configurations'],
  reducers: () => ({
    selectedPipelineId: ['', {
      selectPipeline: (_, {
        pipeline
      }) => pipeline
    }]
  }),
  selectors: ({
    selectors
  }) => ({
    pipelines: [() => [selectors.indexPipelinesData], indexPipelines => {
      return indexPipelines !== null && indexPipelines !== void 0 ? indexPipelines : {};
    }],
    pipelineNames: [() => [selectors.pipelines], pipelines => {
      return Object.keys(pipelines).sort();
    }],
    selectedPipeline: [() => [selectors.selectedPipelineId, selectors.pipelines], (selectedPipelineId, pipelines) => {
      if (pipelines.hasOwnProperty(selectedPipelineId)) {
        return pipelines[selectedPipelineId];
      }
      return undefined;
    }],
    selectedPipelineJSON: [() => [selectors.selectedPipeline], selectedPipeline => {
      if (selectedPipeline) {
        return JSON.stringify(selectedPipeline, null, 2);
      }
      return '';
    }]
  })
});
exports.IndexPipelinesConfigurationsLogic = IndexPipelinesConfigurationsLogic;