/**
 * amberstone
 * @author arcturus (contact@sharlayan.net / https://info.drk.st/about)
 * @version 1.1.3
 */

function pad(num, len = 2) {
  return num.toFixed(0).padStart(len, '0');
}

function serializeForm(form) {
  var formData = new FormData(form);
  var params = new URLSearchParams();

  formData.forEach(function (value, key) {
    params.append(key, value);
  });

  return params.toString();
}

function createHtmlFromJson(jsonData) {
  function createElementRecursive(data) {
    if (typeof data !== 'object' || data === null) {
      return document.createTextNode(String(data));
    }

    const element = createElement(data.type || 'div', data);

    if (data.children) {
      if (Array.isArray(data.children)) {
        data.children.forEach(child => {
          element.appendChild(createElementRecursive(child));
        });
      } else {
        element.appendChild(createElementRecursive(data.children));
      }
    }

    return element;
  }

  return createElementRecursive(jsonData);
}

function createElement(type, data) {
  const elem = document.createElement(type);
  if (typeof data === 'object') {
    if (data.hasOwnProperty('classList')) {
      if (Array.isArray(data.classList)) {
        for (const cl of data.classList) {
          elem.classList.add(cl);
        }
      } else if (typeof data.classList === 'string') {
        elem.classList.add(data.classList);
      }
    }

    if (data.hasOwnProperty('css')) {
      if (typeof data.css === 'object') {
        for (const css in data.css) {
          elem.style.setProperty(css, data.css[css]);
        }
      }
    }

    if (data.hasOwnProperty('textContent')) {
      elem.textContent = data.textContent;
    }

    if (data.hasOwnProperty('innerHTML')) {
      elem.innerHTML = data.innerHTML;
    }

    if (data.hasOwnProperty('attributes')) {
      if (typeof data.attributes === 'object') {
        for (const attr in data.attributes) {
          elem.setAttribute(attr, data.attributes[attr]);
        }
      }
    }
  } else if (Array.isArray(data) && data.length > 0) {
    for (const cl of data) {
      elem.classList.add(cl);
    }
  } else if (typeof data === 'string') {
    elem.classList.add(data);
  }
  return elem;
}

function sendRequest(url, data, type, callback, useUrlEncoded = true) {
  var xhr = new XMLHttpRequest();
  xhr.open(type, url, true);

  if (useUrlEncoded) {
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    data = new URLSearchParams(data).toString();
  } else {
    xhr.setRequestHeader('Content-Type', 'application/json');
    data = JSON.stringify(data);
  }

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        callback(null, xhr.responseText);
      } else {
        callback(xhr.statusText, null);
      }
    }
  };
  xhr.send(type === 'POST' ? data : null);
}
