function findElement (name, attrs) {
  const attrString = Object.entries(attrs).map(([k, v]) => `[${k}="${v}"]`).join('')
  const selector = `${name}${attrString}`

  return document.querySelector(selector)
}

function setAttrs (element, attrs) {
  for (const [k, v] of Object.entries(attrs)) {
    // Set only if different. Prevents re-setting styles.
    if (element.getAttribute(k) !== v) {
      element.setAttribute(k, v)
    }
  }
}

export default function updateHead (name, attrsToSearch, attrsToSet) {
  const remove = Object.values(attrsToSet).every(a => a === null || a === undefined)
  let element = findElement(name, attrsToSearch)

  if (remove) {
    element?.remove()
    return
  }

  if (!element) {
    // Create element if does not exist.
    element = document.createElement(name)
    setAttrs(element, attrsToSearch)
    document.head.appendChild(element)
  }

  setAttrs(element, attrsToSet)
}
