import { emitEvent } from "./events.js";

export function getElements(dataType, dataValue, {
  additionalDataFilters = [],
  additionalPropertyFilters = [],
  element = document,
} = {}) {
  // props: { additionalDataFilters: [key, value][], additionalPropertyFilters: [key, value][] }

  const queryString = [
    ...[[dataType, dataValue], ...additionalDataFilters]
          .map(([k, v]) => [`data-${k}`, v]),
    ...additionalPropertyFilters,
  ].map(([k, v]) => v === '*' ? `[${k}]` : `[${k}='${v}']`).join("");
  return element.querySelectorAll(queryString);
}

export function addEventToElement(dataType, dataValue, event, callback, props = {}) {
  getElements(dataType, dataValue, props)
      .forEach(e => e.addEventListener(event, callback));
}

export function addEventToInput(dataValue, event, callback, props = {}) {
  addEventToElement("input", dataValue, event, callback, props);
}
export function addEventToButton(dataValue, event, callback, props = {}) {
  addEventToElement("button", dataValue, event, callback, props);
}

export function emitOnButtonClick(dataValue, eventName, props = {}) {
  addEventToButton(dataValue, "click", e => emitEvent(eventName, e), props);
}

export function setText(dataValue, text, props = {}) {
  getElements("text", dataValue, props)
      .forEach(e => e.innerText = text);
}

export function debounce(fn, milliseconds = 200) {
  let timeout = null;
  return (...e) => {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => fn(...e), milliseconds);
  }
}
