"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createEditIndexPatternPageStateContainer = createEditIndexPatternPageStateContainer;
var _history = require("history");
var _public = require("@kbn/kibana-utils-plugin/public");
/*
 * 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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

/**
 * Create state container with sync config for tab navigation specific for edit_index_pattern page
 */
function createEditIndexPatternPageStateContainer({
  defaultTab,
  useHashedUrl
}) {
  const history = (0, _history.createHashHistory)();
  // query param to store app state at
  const stateStorageKey = '_a';
  // default app state, when there is no initial state in the url
  const defaultState = {
    tab: defaultTab
  };
  const kbnUrlStateStorage = (0, _public.createKbnUrlStateStorage)({
    useHash: useHashedUrl,
    history
  });
  // extract starting app state from URL and use it as starting app state in state container
  const initialStateFromUrl = kbnUrlStateStorage.get(stateStorageKey);
  const stateContainer = (0, _public.createStateContainer)({
    ...defaultState,
    ...initialStateFromUrl
  }, {
    setTab: state => tab => ({
      ...state,
      tab
    })
  }, {
    tab: state => () => state.tab
  });
  const {
    start,
    stop
  } = (0, _public.syncState)({
    storageKey: stateStorageKey,
    stateContainer: {
      ...stateContainer,
      // state syncing utility requires state containers to handle "null"
      set: state => state && stateContainer.set(state)
    },
    stateStorage: kbnUrlStateStorage
  });

  // makes sure initial url is the same as initial state (this is not really required)
  kbnUrlStateStorage.set(stateStorageKey, stateContainer.getState(), {
    replace: true
  });
  return {
    startSyncingState: start,
    stopSyncingState: stop,
    setCurrentTab: newTab => stateContainer.transitions.setTab(newTab),
    getCurrentTab: () => stateContainer.selectors.tab()
  };
}