
class CreateDialog {

    static END_POINT = "index.php?option=com_baforms&task=form.createForm"

    constructor() {
        this.submitBtn = document.querySelector('.create-button')
        this.titleInput = document.querySelector('#ba-title')
        this.setEvents()
    }

    buildUrl(query) {
        const base = Joomla.getOptions('system.paths').baseFull;

        return `${base}index.php?option=com_baforms&${query}`;
    }



    setEvents() {
        this.titleInput.addEventListener('input', event => this.onInput(event));
        this.titleInput.addEventListener('keydown', event => this.onKeyDown(event));
        this.submitBtn.addEventListener('click', event => this.osSubmit(event));
    }

    onInput() {
        const action = this.titleInput.value.trim() ? 'add' : 'remove';
        this.submitBtn.classList[action]('active-button');
    }

    osSubmit(event) {
        event.preventDefault();
        this.submit();
    }

    async submit() {
        if (!this.submitBtn.classList.contains('active-button') || this.submited) {
            return;
        }

        this.submited = true;
        const module = await import('../modules/Request.js');
        const text = await module.default.post(this.buildUrl('task=form.createForm'), {
            title : this.titleInput.value.trim()
        }).catch(e => {
            console.error(e);
            this.submited = false;
        })

        window.location.href = this.buildUrl(`view=form&id=${text}`);
    }

    onKeyDown(event) {
        if (event.keyCode != 13) {
            return;
        }

        event.preventDefault();
        event.stopPropagation();
        this.submit();
    }
}


document.addEventListener('DOMContentLoaded', function(){
    new CreateDialog();
});