// `items` is an array of which `item` is a member
// `item` must let us read/write property `hidden`
// `parentEl` is the containing element for `itemEl`
// `itemEl` is the 
//
// The idea is that item remains a member of items, but
// its elementmay be added and removed from the parent element.
// We use the items array to determine the placement of itemEl
export function show({items, item, parentEl, itemEl}) {
  if (items.length < 2) {
    parentEl.appendChild(itemEl);
    return;
  }
  // To determine placement,
  // Start with our index in the toolbar tools;
  // iterate through toolbar tools before this one, 
  // and subtract hidden ones from the index.

  let countHidden = 0;
  let index = items.indexOf(item);
  for (let i = 0; i < index; i++) {
    const sibling = items[i];
    if (sibling.hidden) countHidden += 1;
  }
  index -= countHidden;

  // Now we need to find our place.
  // Add to parent using insertBefore.
  let idx = 0;
  let nextEl = parentEl.firstChild;
  while (idx < index) {
    nextEl = nextEl.nextSibling;
    idx += 1;
  }
  parentEl.insertBefore(itemEl, nextEl);
  item.hidden = false;
}

export function hide({items, item, parentEl, itemEl}) {
  if (items.indexOf(item) < 0) return;
  parentEl.removeChild(itemEl);
  item.hidden = true;
}

// Copied from https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
export async function hash(text) {
  const msgUint8 = new TextEncoder().encode(text); // encode as (utf-8) Uint8Array
  const hashBuffer = await window.crypto.subtle.digest("SHA-256", msgUint8); // hash the message
  const hashHex = new Uint8Array(hashBuffer).toHex(); // Convert ArrayBuffer to hex string.
  return hashHex;
}
