/* 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 { $, addClass, on } from 'uikit-util';
import WidgetType from '../WidgetType';
import SourceWidgetDropdown from './SourceWidgetDropdown.vue';
import { composed } from '../state';
import SourceWidgetComponent from './SourceWidget.vue';

let activeWidget;
const widgets = {};

export default class SourceWidget extends WidgetType {
    constructor({ id, range }) {
        super({ range });

        this.id = id;
        this.type = 'source';
        this.literal = `{{ sources.${id} }}`;

        widgets[this.id] = this;
    }
    toDOM(view) {
        const wrap = this.createWrapperDom(view);
        const { vm, sources } = view.state.field(composed);

        addClass(wrap, 'uk-button-default');

        this.vm = new Vue({
            parent: vm,
            el: wrap.appendChild($('<span/>')),
            extends: SourceWidgetComponent,
            propsData: { value: sources[this.id] },
        });

        return (this.dom = wrap);
    }
    showdrop() {
        const { vm, sources } = this.view.state.field(composed);

        this.drop = vm.$dropdown(SourceWidgetDropdown, {
            values: sources[this.id],
        });

        const off = on(this.drop.$el, 'hide', () => {
            if (activeWidget === this) {
                this.blur();
                activeWidget = null;
            }

            off();
        });

        const target = vm.$el;

        this.drop.show(target, {
            classes: 'yo-dropdown',
            boundaryX: target.closest('.yo-sidebar-fields > *') || target,
        });
    }
    focus() {
        super.focus();
        this.showdrop();

        activeWidget = this;
    }
    remove() {
        this.view.dispatch({
            changes: { ...this.range, insert: '' },
            selection: { anchor: this.range.from },
        });

        this.view.focus();
    }
    destroy() {
        super.destroy();
        this.drop?.$destroy();
        this.vm.$destroy();

        delete widgets[this.id];
    }
}
