/*
 * Demo Oracle — filtres et tri du rapport des parametres.
 *
 * Portage de modules/oracle/assets/js/report-config.js, ampute de tout ce qui
 * ecrivait : l'aide AJAX oraPost(), le bouton de remise par defaut et la
 * fenetre d'edition en ligne. Il ne reste que du filtrage et du tri, cote
 * navigateur, sans le moindre appel reseau.
 */
(function () {
    'use strict';

    var CFG = window.DemoOracleReport && window.DemoOracleReport.config;
    if (!CFG) return;

    // ── NLS filter + sort ─────────────────────────────────────────────────────
    if (CFG.hasNls) {
        var nlsTable  = document.getElementById('nls-table');
        if (nlsTable) {
            var nlsTbody  = nlsTable.querySelector('tbody');
            var nlsAllRows = Array.from(nlsTbody.querySelectorAll('tr'));
            var nlsCountEl = document.getElementById('nls-f-count');

            function applyNlsFilters() {
                var fName = document.getElementById('nls-f-name').value.toLowerCase().trim();
                var fDiff = document.getElementById('nls-f-diff').checked;
                var visible = 0;
                nlsAllRows.forEach(function (tr) {
                    var d = tr.dataset;
                    if (fName && d.param.indexOf(fName) === -1) { tr.style.display = 'none'; return; }
                    if (fDiff && d.diff !== '1')                { tr.style.display = 'none'; return; }
                    tr.style.display = ''; visible++;
                });
                nlsCountEl.textContent = '(' + visible + ')';
            }

            document.getElementById('nls-f-name').addEventListener('input', applyNlsFilters);
            document.getElementById('nls-f-diff').addEventListener('change', applyNlsFilters);
            applyNlsFilters();

            // Sort
            var nlsSortState = { col: -1, asc: true };
            nlsTable.querySelectorAll('th.sortable').forEach(function (th) {
                th.style.cursor = 'pointer';
                th.addEventListener('click', function () {
                    var col = parseInt(th.dataset.col);
                    nlsSortState.asc = (nlsSortState.col === col) ? !nlsSortState.asc : true;
                    nlsSortState.col = col;
                    nlsTable.querySelectorAll('th.sortable .sort-arrow').forEach(function (a) { a.textContent = ''; });
                    th.querySelector('.sort-arrow').textContent = nlsSortState.asc ? ' ▲' : ' ▼';
                    var sorted = nlsAllRows.slice().sort(function (a, b) {
                        var av = (a.cells[col] ? a.cells[col].textContent : '').trim();
                        var bv = (b.cells[col] ? b.cells[col].textContent : '').trim();
                        return nlsSortState.asc ? av.localeCompare(bv) : bv.localeCompare(av);
                    });
                    sorted.forEach(function (tr) { nlsTbody.appendChild(tr); });
                    nlsAllRows.length = 0;
                    sorted.forEach(function (tr) { nlsAllRows.push(tr); });
                });
            });
        }
    }

    // ── Parameters filter + sort + AJAX ───────────────────────────────────────
    if (!CFG.hasRows) return;

    var table  = document.getElementById('cfg-table');
    if (!table) return;
    var tbody  = table.querySelector('tbody');
    var allRows = Array.from(tbody.querySelectorAll('tr'));
    var countEl = document.getElementById('f-count');

    // ── Filtering ─────────────────────────────────────────────────────────────
    function applyFilters() {
        var fBasic    = document.getElementById('f-isbasic').checked;
        var fModified = document.getElementById('f-ismodified').checked;
        var fType     = document.getElementById('f-type').value;
        var fName     = document.getElementById('f-name').value.toLowerCase().trim();
        var modeCbs   = Array.from(document.querySelectorAll('.f-mode'));
        var checkedModes   = modeCbs.filter(function (cb) { return cb.checked; }).map(function (cb) { return cb.value; });
        var allModesChecked = checkedModes.length === modeCbs.length;

        var visible = 0;
        allRows.forEach(function (tr) {
            var d = tr.dataset;
            if (fBasic    && d.isbasic   !== '1') { hide(tr); return; }
            if (fModified && d.ismodified !== '1') { hide(tr); return; }
            if (fType !== '' && d.type   !== fType) { hide(tr); return; }
            if (fName !== '' && d.name.indexOf(fName) === -1) { hide(tr); return; }
            // Mode filter: when not all checked, at least one selected mode must be applicable
            if (!allModesChecked && checkedModes.length > 0) {
                var match = checkedModes.some(function (m) { return d[m] === '1'; });
                if (!match) { hide(tr); return; }
            }
            show(tr);
            visible++;
        });
        countEl.textContent = '(' + visible + ')';
    }

    function hide(tr) { tr.style.display = 'none'; }
    function show(tr) { tr.style.display = ''; }

    // Bind filter controls
    document.getElementById('f-isbasic').addEventListener('change', applyFilters);
    document.getElementById('f-ismodified').addEventListener('change', applyFilters);
    document.getElementById('f-type').addEventListener('change', applyFilters);
    document.getElementById('f-name').addEventListener('input', applyFilters);
    document.querySelectorAll('.f-mode').forEach(function (cb) {
        cb.addEventListener('change', applyFilters);
    });
    document.getElementById('f-reset-btn').addEventListener('click', function () {
        document.getElementById('f-isbasic').checked    = true;
        document.getElementById('f-ismodified').checked = true;
        document.getElementById('f-type').value         = '';
        document.getElementById('f-name').value         = '';
        document.querySelectorAll('.f-mode').forEach(function (cb) { cb.checked = true; });
        applyFilters();
    });

    // Apply on load
    applyFilters();

    // ── Column sort ───────────────────────────────────────────────────────────
    var sortState = { col: -1, asc: true };
    table.querySelectorAll('th.sortable').forEach(function (th) {
        th.style.cursor = 'pointer';
        th.addEventListener('click', function () {
            var col = parseInt(th.dataset.col);
            sortState.asc = (sortState.col === col) ? !sortState.asc : true;
            sortState.col = col;

            table.querySelectorAll('th.sortable .sort-arrow').forEach(function (a) { a.textContent = ''; });
            th.querySelector('.sort-arrow').textContent = sortState.asc ? ' ▲' : ' ▼';

            var sorted = allRows.slice().sort(function (a, b) {
                var av = (a.cells[col] ? a.cells[col].textContent : '').trim();
                var bv = (b.cells[col] ? b.cells[col].textContent : '').trim();
                return sortState.asc ? av.localeCompare(bv) : bv.localeCompare(av);
            });
            sorted.forEach(function (tr) { tbody.appendChild(tr); });
            // Re-sync allRows order so further sorts stay consistent
            allRows.length = 0;
            sorted.forEach(function (tr) { allRows.push(tr); });
        });
    });
})();
