"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.mountFlashMessagesLogic = exports.FlashMessagesLogic = void 0;
var _kea = require("kea");
var _kibana = require("../kibana");
/*
 * 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 convertToArray = messages => !Array.isArray(messages) ? [messages] : messages;
const FlashMessagesLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'flash_messages_logic'],
  actions: {
    setFlashMessages: messages => ({
      messages: convertToArray(messages)
    }),
    clearFlashMessages: () => null,
    setQueuedMessages: messages => ({
      messages: convertToArray(messages)
    }),
    clearQueuedMessages: () => null,
    addToastMessage: newToast => ({
      newToast
    }),
    dismissToastMessage: removedToast => ({
      removedToast
    }),
    clearToastMessages: () => null,
    setHistoryListener: historyListener => ({
      historyListener
    })
  },
  reducers: {
    messages: [[], {
      setFlashMessages: (_, {
        messages
      }) => messages,
      clearFlashMessages: () => []
    }],
    queuedMessages: [[], {
      setQueuedMessages: (_, {
        messages
      }) => messages,
      clearQueuedMessages: () => []
    }],
    toastMessages: [[], {
      addToastMessage: (toasts, {
        newToast
      }) => [...toasts, newToast],
      dismissToastMessage: (toasts, {
        removedToast
      }) => toasts.filter(({
        id
      }) => id !== removedToast.id),
      clearToastMessages: () => []
    }],
    historyListener: [null, {
      setHistoryListener: (_, {
        historyListener
      }) => historyListener
    }]
  },
  events: ({
    values,
    actions
  }) => ({
    afterMount: () => {
      // On React Router navigation, clear previous flash messages and load any queued messages
      const unlisten = _kibana.KibanaLogic.values.history.listen(() => {
        actions.clearFlashMessages();
        actions.setFlashMessages(values.queuedMessages);
        actions.clearQueuedMessages();
      });
      actions.setHistoryListener(unlisten);
    },
    beforeUnmount: () => {
      const {
        historyListener: removeHistoryListener
      } = values;
      if (removeHistoryListener) removeHistoryListener();
    }
  })
});

/**
 * Mount/props helper
 */
exports.FlashMessagesLogic = FlashMessagesLogic;
const mountFlashMessagesLogic = () => {
  const unmount = FlashMessagesLogic.mount();
  return unmount;
};
exports.mountFlashMessagesLogic = mountFlashMessagesLogic;