export var Multipick = {
    current: null,
    _onPageLoad: () => {
        addGlobalEventListener('change', '[data-popup-multipick] input[name="selection\\[\\]"]', (event) => {
            Multipick.popupUpdate()
        });
    },
    popupUpdate: () => {
        const form = document.getElementById('multipick-form');
        const selection = (new FormData(form)).getAll('selection[]');
        form.querySelector('[data-multipick-selection-count]')
            .innerHTML = selection.length;
    },
    zoom: (el) => {
        const multipick = el.closest('[data-multipick]');
        const selection = 
            new FormData(multipick.closest('form'))
            .getAll(multipick.getAttribute('data-multipick') + '[]');


        activeLoader();
        ajaxSimple(
            multipick.getAttribute('data-multipick-popup'),
            {
                zoomPath: multipick.getAttribute('data-multipick-zoompath'),
                selection: selection,
                // TODO zoomFilter: [], 
            },
            (resp) => {
                window.Multipick.current = multipick;
                activePopup(
                    multipick.getAttribute('data-multipick-zoom-title'),
                    resp,
                    'modal_small'
                );
                desactiveLoader();
            }
        )
    },
    handlePopupSelection: (formPopup) => {
        const multipick = Multipick.current;
        ajaxSimple(
            window.oxaproc.path.multipickReadEntity,
            {
                zoomPath: multipick.getAttribute('data-multipick-zoompath'),
                selection: (new FormData(formPopup)).getAll('selection[]'),
            },
            (result) => {
                const listField = result.config.listField;
                Multipick.removeAll(multipick);
                for (const entity of result.listEntity) {
                    // TODO : handle listField
                    Multipick._addRow(multipick, entity);
                }
            }
        );
        
        desactivePopup();
    },
    _addRow: (multipick, entity) => {
        // Prevent duplicate entry
        const duplicate = window.Multipick.current.querySelector(
            'input[data-multipick-subinput][value="' + CSS.escape(entity.id) + '"]'
        );
        if (duplicate) {
            return;
        }

        // Render new row
        let tpl = getJsTemplate(multipick.getAttribute('data-multipick-tpl'));
    
        const mapPlaceholder = {
            __INPUT_NAME__: multipick.getAttribute('data-multipick'),
        };
        for (const k in entity) {
            mapPlaceholder['__PLHLD_' + k + '__'] = entity[ k ];
        }
        tpl = renderJsTemplate2(tpl, mapPlaceholder);
    
        let tmp = document.createElement('table'); // Since root element is a <tr>, a <table> is requried
        
        // Template to DOM
        tmp.innerHTML = tpl;
        let row = tmp.querySelector('tr');
    
        // Insert template
        const table = multipick;
        const tbody = table.querySelector('tbody');
        tbody.append(row);
        
        table.scrollIntoView({behavior: 'smooth', block: 'start'}); // TODO : move somewhere else
        Multipick._updateEmptyLabel(multipick);
    },
    removeAll: (multipick) => {
        multipick.querySelector(':scope>tbody').innerHTML = '';
        Multipick._updateEmptyLabel(multipick);
    },
    removeRow: (row) => {
        const multipick = row.closest('[data-multipick]');
    
        row.remove();
    
        Multipick._updateEmptyLabel(multipick);
    },
    _updateEmptyLabel: (multipick) => {
        // Case : table is empty
        const tbody = multipick.querySelector(':scope>tbody');
        const trEmptyLabel = Multipick.getEmptyLabel(multipick);
        trEmptyLabel.style.display = (tbody.children.length == 0 ? '' : 'none');
    },
    getEmptyLabel: (multipick) => {
        return multipick.querySelector(':scope>tbody>tr>td[data-label-empty]').closest('tr');
    },
}

