"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.updateMetaData = exports.syncBreadcrumbSaga = exports.metaDataSelector = exports.metaDataReducer = void 0;
var _typescriptFsa = _interopRequireDefault(require("typescript-fsa"));
var _typescriptFsaReducers = require("typescript-fsa-reducers");
var _effects = require("redux-saga/effects");
var _i18n = require("@kbn/i18n");
var _global = require("./global");
var _url = require("../services/url");
/*
 * 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/metaData');
const updateMetaData = actionCreator('UPDATE_META_DATA');
exports.updateMetaData = updateMetaData;
const initialMetaData = {
  title: _i18n.i18n.translate('xpack.graph.newGraphTitle', {
    defaultMessage: 'Unsaved graph'
  }),
  description: ''
};
const metaDataReducer = (0, _typescriptFsaReducers.reducerWithInitialState)(initialMetaData).case(_global.reset, () => initialMetaData).case(updateMetaData, (oldMetaData, newMetaData) => ({
  ...oldMetaData,
  ...newMetaData
})).build();
exports.metaDataReducer = metaDataReducer;
const metaDataSelector = state => state.metaData;

/**
 * Saga updating the breadcrumb when the shown workspace changes.
 */
exports.metaDataSelector = metaDataSelector;
const syncBreadcrumbSaga = ({
  chrome,
  changeUrl
}) => {
  function* syncBreadcrumb() {
    const metaData = metaDataSelector(yield (0, _effects.select)());
    (0, _url.setBreadcrumbs)({
      chrome,
      metaData,
      navigateTo: path => {
        // TODO this should be wrapped into canWipeWorkspace,
        // but the check is too simple right now. Change this
        // once actual state-diffing is in place.
        changeUrl(path);
      }
    });
  }
  return function* () {
    // initial sync
    yield (0, _effects.call)(syncBreadcrumb);
    yield (0, _effects.takeLatest)(updateMetaData.match, syncBreadcrumb);
  };
};
exports.syncBreadcrumbSaga = syncBreadcrumbSaga;