document.getElementById('searchButton').addEventListener('click', function () {
    const username = document.getElementById('username').value;
    const level = document.getElementById('level').value;
    const message = document.getElementById('message').value;
    const logEvent = document.getElementById('logevent').value;

    fetch(`/api/logs?username=${username}&level=${level}&message=${message}&logEvent=${logEvent}`)
        .then(response => response.json())
        .then(data => {
            const tableBody = document.querySelector('#logsTable tbody');
            tableBody.innerHTML = '';

            data.forEach(log => {
                const row = document.createElement('tr');

                row.innerHTML = `
                    <td>${log.id}</td>
                    <td>${log.message}</td>
                    <td>${log.level}</td>
                    <td>${log.timeStamp}</td>
                    <td>${log.userName}</td>
                    <td>${JSON.stringify(JSON.parse(log.logEvent), null, 2)}</td>
                `;

                tableBody.appendChild(row);
            });
        });

});

$('#logEventModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var logContent = button.data('log');
    var modal = $(this);
    const base64 = button.data('log');
    let decoded = "";
    const decodedArrayBuffer = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
    const decodedString = new TextDecoder().decode(decodedArrayBuffer);
    decoded = decodedString;// JSON.stringify(JSON.parse(decodedString));
    parseJSON(decoded);
});
function renderJson(container, obj) {
    container.innerHTML = '';          // clear
    container.setAttribute('dir', 'ltr');

    function walk(parent, value) {
        if (value === null || typeof value !== 'object') {
            // leaf node (string, number, boolean, null)
            const span = document.createElement('span');
            const text = JSON.stringify(value);
            span.textContent = text;
            // detect if it’s a quoted string starting with a Persian char
            if (/^"[\u0600-\u06FF]/.test(text)) {
                span.setAttribute('dir', 'rtl');
            } else {
                span.setAttribute('dir', 'ltr');
            }
            span.style.unicodeBidi = 'isolate';
            parent.appendChild(span);
            return;
        }
        // object or array
        const isArray = Array.isArray(value);
        parent.appendChild(document.createTextNode(isArray ? '[' : '{'));
        const entries = isArray ? value : Object.entries(value);
        entries.forEach((item, i) => {
            if (!isArray) {
                // key
                const keySpan = document.createElement('span');
                keySpan.textContent = `"${item[0]}"`;
                keySpan.setAttribute('dir', 'ltr');
                keySpan.style.unicodeBidi = 'isolate';
                parent.appendChild(keySpan);
                parent.appendChild(document.createTextNode(': '));
                walk(parent, item[1]);
            } else {
                walk(parent, item);
            }
            if (i < entries.length - 1) {
                parent.appendChild(document.createTextNode(', '));
            }
        });
        parent.appendChild(document.createTextNode(isArray ? ']' : '}'));
    }

    walk(container, obj);
}
function parseJSON(decoded) {
    // const jsonInput = document.getElementById('jsonInput').value;
    const viewer = document.getElementById('jsonViewer');

    try {
        const parsedJSON = JSON.parse(decoded);
        viewer.innerHTML = '';
        viewer.appendChild(buildTree(parsedJSON));
        addToggleListeners();
    } catch (e) {
        console.error(`Error parsing JSON: ${e.message}`);
        viewer.innerHTML = '';
    }
}

function buildTree(data, key) {
    const node = document.createElement('div');
    node.className = 'json-node';

    if (key) {
        const keyElement = document.createElement('span');
        keyElement.className = 'json-key';
        keyElement.textContent = `${key}: `;
        node.appendChild(keyElement);
    }

    if (typeof data === 'object' && data !== null) {
        const isArray = Array.isArray(data);
        const type = isArray ? 'array' : 'object';
        const items = Object.entries(data || {});

        const toggle = document.createElement('span');
        toggle.className = 'toggle';
        toggle.textContent = '▶';
        node.prepend(toggle);

        const bracket = document.createElement('span');
        bracket.textContent = isArray ? '[' : '{';
        node.appendChild(bracket);

        if (items.length > 0) {
            const children = document.createElement('div');
            children.className = 'children';
            items.forEach(([childKey, value], index) => {
                const child = buildTree(value, isArray ? null : childKey);
                children.appendChild(child);
                if (index < items.length - 1) {
                    children.appendChild(document.createTextNode(','));
                }
            });
            node.appendChild(children);
        }

        const closingBracket = document.createElement('span');
        closingBracket.textContent = isArray ? ']' : '}';
        node.appendChild(closingBracket);

        node.classList.add(type);
    } else {
        const valueElement = document.createElement('span');
        let type = typeof data;
        if (data === null) type = 'null';

        valueElement.className = `json-${type}`;
        valueElement.textContent = formatValue(data);
        node.appendChild(valueElement);
    }

    return node;
}

function formatValue(value) {
    if (value === null) return 'null';
    if (typeof value === 'string') return `"${value}"`;
    return value.toString();
}

function addToggleListeners() {
    document.querySelectorAll('.toggle').forEach(toggle => {
        toggle.addEventListener('click', function () {
            this.parentElement.classList.toggle('collapsed');
            this.textContent = this.parentElement.classList.contains('collapsed') ? '▶' : '▼';
        });
    });
}