export var InputTable = {
    getNextId: (table, inputPrefix) => {
        let i = 0;
        while (table.querySelector(
            '[name^="'
            + CSS.escape(inputPrefix+'['+i+']')
            +'"]'
        ) != null) {
            i++;
        }
        return i;
    },
    addRow: (el, inputPrefix) => {
        const table = el.closest('[data-inputtable]');

        let tpl = table.nextElementSibling.textContent;
    
        tpl = tpl.replaceAll(
            table.getAttribute('data-inputtable-placeholder'),
            InputTable.getNextId(table, inputPrefix)
        );
    
        let tmp = document.createElement('table'); // Since root element is a <tr>, a <table> is requried
    
        // Decode html entities
        tmp.innerHTML = tpl; 
        tpl = tmp.textContent;
    
        // Template to DOM
        tmp.innerHTML = tpl; 
        let row = tmp.querySelector('tr');
        row.classList.add('anim-new-row-flash');
    
        // Insert template
        const tbody = table.querySelector('tbody');
        tbody.append(row);
        // TODO : focus first input ?
    
        row.scrollIntoView({block: 'center'});
    
        // Note : we use :scope>... to prevent selecting a posible child table  
        table.querySelector(':scope>tbody>tr>td[data-label-empty]').style.display = 'none';

        table.dispatchEvent(new CustomEvent('input-table-change', {
            detail: {
                table: table,
                row: row,
                type: 'add',
            },
            bubbles: true,
        }));
    },
    removeRow: (row) => {
    
        const table = row.closest('table');
        const tbody = table.querySelector('tbody');
    
        row.remove();
    
        // Case : table is empty
        if (tbody.children.length == 1) {
            table.querySelector(':scope>tbody>tr>td[data-label-empty]').style.display = '';
        }

        table.dispatchEvent(new CustomEvent('input-table-change', {
            detail: {
                table: table,
                row: row,
                type: 'remove',
            },
            bubbles:true,
        }));
    },
}