import { Plugin, PluginKey } from "prosemirror-state";
import { getTextInputHandler } from "./factory-helpers/text-input-handler";
import { getAppendTransactionHandler } from "./factory-helpers/append-transaction-handler";
import { sendTriggerEvent } from "./factory-helpers/send-trigger-event";
export const createTriggerPlugin = (triggerCharacters, contentConverter) => {
    let pluginView = null;
    let activeTrigger = null;
    const getCurrentView = () => {
        return pluginView;
    };
    const getActiveTrigger = () => {
        return activeTrigger;
    };
    const resetActiveTrigger = () => {
        activeTrigger = null;
    };
    const updateActiveTrigger = (trigger) => {
        activeTrigger = trigger;
    };
    const textInputHandler = getTextInputHandler(contentConverter, triggerCharacters, updateActiveTrigger);
    const appendTransactionHandler = getAppendTransactionHandler(getCurrentView, getActiveTrigger, resetActiveTrigger, contentConverter);
    return new Plugin({
        key: new PluginKey('triggerPlugin'),
        view: (view) => {
            pluginView = view;
            return {};
        },
        state: {
            init: () => {
                return {};
            },
            apply: (transaction) => {
                if (transaction.getMeta('stopTrigger')) {
                    sendTriggerEvent('triggerStop', pluginView, contentConverter, activeTrigger, '');
                    resetActiveTrigger();
                }
                return {};
            },
        },
        props: {
            handleTextInput: textInputHandler,
        },
        appendTransaction: appendTransactionHandler,
    });
};
