/* 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';
import { EditorSelection } from '@codemirror/state';

export default ViewPlugin.fromClass(
    class {
        constructor(view) {
            Vue.events.on('essentialsAddComposableCondition', (e, type) => {
                const id = uuid();
                const { conditions } = view.state.field(composed);
                const anchor = view.state.selection.main.anchor;

                Vue.set(conditions, id, {});

                const from = view.state.selection.main.anchor || view.state.doc.length;
                const insert = [
                    `{{ if conditions.${id} }}`,
                    'content',
                    `{{ /if conditions.${id} }}`,
                ];

                view.dispatch({
                    changes: {
                        from,
                        insert: anchor ? insert.join('') : `\n${insert.join('')}`,
                    },
                    selection: EditorSelection.range(
                        from + insert[0].length + 1,
                        from + insert[0].length + insert[1].length + 1
                    ),
                });

                view.focus();

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

                return;
            });
        }
    }
);
