"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.updateSettings = exports.syncSettingsSaga = exports.settingsSelector = exports.advancedSettingsReducer = void 0;
var _typescriptFsa = _interopRequireDefault(require("typescript-fsa"));
var _dist = require("typescript-fsa-reducers/dist");
var _effects = require("redux-saga/effects");
var _global = require("./global");
var _datasource = require("./datasource");
/*
 * 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 actionCreator = (0, _typescriptFsa.default)('x-pack/graph/advancedSettings');
const updateSettings = actionCreator('UPDATE_SETTINGS');
exports.updateSettings = updateSettings;
const initialSettings = {
  useSignificance: true,
  sampleSize: 2000,
  timeoutMillis: 5000,
  sampleDiversityField: undefined,
  maxValuesPerDoc: 1,
  minDocCount: 3
};
const advancedSettingsReducer = (0, _dist.reducerWithInitialState)(initialSettings).case(_global.reset, () => initialSettings).cases([_datasource.requestDatasource, _datasource.setDatasource], ({
  sampleDiversityField,
  ...restSettings
}) => ({
  ...restSettings
})).case(updateSettings, (_oldSettings, newSettings) => newSettings).build();
exports.advancedSettingsReducer = advancedSettingsReducer;
const settingsSelector = state => state.advancedSettings;

/**
 * Saga making sure the advanced settings are always synced up to the workspace instance.
 *
 * Won't be necessary once the workspace is moved to redux
 */
exports.settingsSelector = settingsSelector;
const syncSettingsSaga = ({
  getWorkspace,
  notifyReact
}) => {
  function* syncSettings(action) {
    const workspace = getWorkspace();
    if (!workspace) {
      return;
    }
    workspace.options.exploreControls = action.payload;
    notifyReact();
  }
  return function* () {
    yield (0, _effects.takeLatest)(updateSettings.match, syncSettings);
  };
};
exports.syncSettingsSaga = syncSettingsSaga;