/* Essentials YOOtheme Pro 2.2.16 build 0813.1608; ZOOlanders https://www.zoolanders.com; Copyright (C) Joolanders, SL; http://www.gnu.org/licenses/gpl.html GNU/GPL */

import Vue from 'vue';
import { uuid } from '../util';
import { composed } from '../state';
import { ViewPlugin } from '@codemirror/view';

export default ViewPlugin.fromClass(
    class {
        constructor(view) {
            Vue.events.on('yeAddComposableSource', (e, value) => {
                const id = uuid();
                const { sources } = view.state.field(composed);

                const insert = `{{ sources.${id} }}`;

                Vue.set(sources, id, value);

                if (view.state.selection?.ranges?.[0]) {
                    view.dispatch({
                        changes: {
                            from: view.state.selection.ranges[0].from,
                            to: view.state.selection.ranges[0].to,
                            insert,
                        },
                    });
                } else {
                    view.dispatch({
                        changes: {
                            from: view.state.selection.main.anchor || view.state.doc.length,
                            insert,
                        },
                    });
                }

                setTimeout(() => {
                    // lastWidget.vm?.edit();
                }, 1);

                return;
            });
        }
    }
);
