/* 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 { EditorView } from 'codemirror';
import { EditorState } from '@codemirror/state';
import { activeWidget, composed } from './state';
// import ConditionDecorator from './condition';
import SourceDecorator from './source';

// cancel selection after dragged widget has been dropped
const unselectDraggedWidget = EditorState.transactionFilter.of((tr) => {
    const isMoveDrop = tr.annotations.some((a) => a.value === 'move.drop');

    if (isMoveDrop) {
        const selected = tr.newDoc
            .toString()
            .substring(tr.newSelection.main.from, tr.newSelection.main.to);

        // if match any widget
        if (selected.match(/{{.*}}/)) {
            return [
                tr,
                {
                    selection: { anchor: tr.state.selection.ranges[0].from },
                    sequential: true,
                },
            ];
        }
    }

    return tr;
});

export default function ({ vm, sources, conditions }) {
    return [
        SourceDecorator,
        // ConditionDecorator,
        activeWidget,
        unselectDraggedWidget,
        composed.init(() => ({ vm, sources, conditions })),
        EditorView.domEventHandlers({
            dragover(e) {
                // enforce drag effect
                e.dataTransfer.dropEffect = 'move';
                e.dataTransfer.effectAllowed = 'move';
                e.preventDefault();
            },
        }),
    ];
}
