const DEL = 'DELETE';
const PATCH = 'PATCH';
const POST = 'POST';

// remove all children from element, leave only the first <keep> children
function clearElement(key,keep = 1){
    var elem = key instanceof Element ? key : get(key);
    while (elem.childElementCount > keep) elem.removeChild(elem.lastChild);
    return elem;
}

function create(type,code){
    var elem = document.createElement(type);
    if (code) elem.innerHTML = code;
    return elem;
}

function disable(id){
    var elem = get(id);
    elem.setAttribute('disabled','disabled');
    return elem;
}

function enable(id){
    var elem = get(id);
    elem.removeAttribute('disabled');
    return elem;
}

function get(id){
    return document.getElementById(id);
}

function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let arr = decodedCookie.split(';');
  for(let i = 0; i <arr.length; i++) {
    let c = arr[i];
    while (c.charAt(0) == ' ') c = c.substring(1);
    if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
  }
  return "";
}

function getValue(id){
    return get(id).value;
}

function hide(id){
    var elem = get(id);
    if (elem) elem.style.display = 'none';
    return elem;
}

function hideAll(clazz){
    var elems = document.getElementsByTagName('*'), i;
    for (i in elems) {
        if((' ' + elems[i].className + ' ').indexOf(' ' + clazz + ' ') > -1)  elems[i].style.display = 'none';
    }
}

function isChecked(id){
    return get(id).checked;
}

function menu(){
    fetch('<? user.api.menu ?>').then(showMenu);
}

// Replacement for Object.toEntries(…)
function paramsToObject(entries) {
  const result = {};
  for(var key of entries) { // each 'entry' is a [key, value] tupple
    result[key[0]] = key[1];
  }
  return result;
}

function redirect(page){
    window.location.href = page;
}

function setText(id, text){
    var elem = get(id);
    elem.innerHTML = text;
    return elem;
}

function setValue(id,newVal){
    var elem = get(id);
    if (elem) elem.value = newVal;
    return elem;
}

function show(id){
    var elem = get(id);
    if (elem) elem.style.display = '';
    return elem;
}

function showAll(clazz){
    var elems = document.getElementsByTagName('*'), i;
    for (i in elems) {
        if((' ' + elems[i].className + ' ').indexOf(' ' + clazz + ' ') > -1)  elems[i].style.display = '';
    }
}

function showError(json){
    var message = json.message;
    var box = show('error');
    box.innerHTML = message;

    var button = document.createElement('button');
    button.innerText = 'ok';
    button.addEventListener('click',() => hide('error'))
    box.appendChild(button);
    box.scrollIntoView();
}

async function showMenu(resp){
    if (resp.ok){
        var menu = get('main_menu');
        var json = await resp.json();
        var entries = json.entries;
        entries.sort((a,b) => a.index - b.index);
        for (var idx in entries){
            var entry = entries[idx];
            menu.insertAdjacentHTML('beforeend','<a class="button" href="'+entry.url+'">'+entry.caption+'</a>');
        }
    }
}

function sortTableColumn(column){
    var table = column;
    var columnIndex = [...column.parentNode.children].indexOf(column);
    while (table.localName != 'table'){
        if (!table.parentNode) return;
        table = table.parentNode;
    }
    var rows = Array.from(table.tBodies[0].rows);
    var asc = table.getAttribute("data-sort-dir") !== "desc";
    table.setAttribute("data-sort-dir", asc ? "desc" : "asc");
    rows.sort(function(a, b) {
        var cellA = a.cells[columnIndex].innerText.trim();
        var cellB = b.cells[columnIndex].innerText.trim();
        var numA = parseFloat(cellA);
        var numB = parseFloat(cellB);
        if (!isNaN(numA) && !isNaN(numB)) return asc ? numA - numB : numB - numA;
        return asc ? cellA.localeCompare(cellB) : cellB.localeCompare(cellA);
    });

    // Append sorted rows back to the tbody
    rows.forEach(function(row) {
        table.tBodies[0].appendChild(row);
    });
}

function spread(json,prefix){
    for (var key in json){
        var val = json[key];
        var id = prefix+"."+key;
        if (typeof val === 'object'){
            spread(val,id);
            continue;
        }
        if (typeof val === 'string') val = val.replaceAll("\n","<br/>\n");
        var tag = get(id);
        if (tag) tag.innerHTML = val;
    }
}
