/**
 * Form inline fields
 * this one is going to be tough!
 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

const formInlineFieldPlugin = {
    initFields(form) {
        this.init(form);
    },
    init(form) {
	this.form = form;
	const inlineFields = form.querySelectorAll('.dp-form-inline-field');
	inlineFields.forEach(fieldWrap => {
	    const hiddenFields = fieldWrap.querySelector('div.hiddenfields');
	    const deleteRecord = function () {
		if (!confirm('Field-Möchten Sie diesen Eintrag wirklich löschen?')) {
		    return;
		}

		const deleteElement = this.closest('div.dp-record-container');
		const deleteId = deleteElement?.dataset.rel;

		if (deleteElement) {
		    deleteElement.remove();
		}

		if (deleteId != null) {
                    const innerForm = form.querySelector('form');
                    if (innerForm) {
                        innerForm.querySelectorAll(`.${deleteId}`).forEach(el => el.remove());
                    }
                }

		// enable hidden field if no records (except dummy)
		if (fieldWrap.querySelectorAll('.dp-record-container').length === 1) {
		    hiddenFields?.querySelector('input.isEmpty')?.removeAttribute('disabled');
		}
	    };

	    const copyItself = function (e) {
		// remove keybinding
		this.removeEventListener('keydown', copyItself);

		const clone = this.cloneNode(true);

		// rebind keydown on clone
		clone.addEventListener('keydown', copyItself);

		// append clone
		fieldWrap.appendChild(clone);

		// remove dummy class from original
		this.classList.remove('dp-record-container-dummy');

		// generate temp name
		const tempName = fieldWrap.querySelectorAll('.dp-record-container').length + 99;

		// update all name attributes
		this.querySelectorAll('[name]').forEach(el => {
		    let name = el.getAttribute('name');
		    if (!name) return;

		    name = name.replace('dummy-', '');
		    name = name.replace('TEMP', tempName);
		    el.setAttribute('name', name);
		});

		// enable delete button
		const deleteBtn = this.querySelector('.dp-sprite.dp-delete');
		if (deleteBtn) {
		    deleteBtn.style.display = '';
		    deleteBtn.addEventListener('click', deleteRecord);
		}
	    };
	    
	    // bind existing delete buttons
	    fieldWrap.querySelectorAll('.dp-record-container:not(.dp-record-container-dummy) .dp-sprite.dp-delete')
		.forEach(el => {
		    el.addEventListener('click', deleteRecord);
		});

	    // bind dummy keydown
	    fieldWrap.querySelectorAll('div.dp-record-container-dummy')
		.forEach(el => {
		    el.addEventListener('keydown', copyItself);
		});
	});
    }
};

IGDATAPOOLFE.addPlugin('formInlineField', formInlineFieldPlugin);

export default formInlineFieldPlugin;
