import { getCurrentInstance } from 'vue';

const filterAvailableInput = (element) => {
    return element.classList.contains('q-field__native') && !element.disabled;
};
const filterAvailableText = (element) => {
    return (
        element.__vueParentComponent.type.name === 'QInput' &&
        element.__vueParentComponent?.attrs?.class !== 'vn-input-date'
    );
};

export default {
    mounted: function () {
        const vm = getCurrentInstance();
        if (vm.type.name === 'QForm') {
            if (!['searchbarForm', 'filterPanelForm'].includes(this.$el?.id)) {
                // AUTOFOCUS
                const elementsArray = Array.from(this.$el.elements);
                const availableInputs = elementsArray.filter(filterAvailableInput);
                const firstInputElement = availableInputs.find(filterAvailableText);

                if (firstInputElement) {
                    firstInputElement.focus();
                }
                const that = this;
                this.$el.addEventListener('keyup', function (evt) {
                    if (evt.key === 'Enter') {
                        const input = evt.target;
                        if (input.type == 'textarea' && evt.shiftKey) {
                            evt.preventDefault();
                            let { selectionStart, selectionEnd } = input;
                            input.value =
                                input.value.substring(0, selectionStart) +
                                '\n' +
                                input.value.substring(selectionEnd);
                            selectionStart = selectionEnd = selectionStart + 1;
                            return;
                        }
                        evt.preventDefault();
                        that.onSubmit();
                    }
                });
            }
        }
    },
};
