import { default as tmpl } from '../templates/character-counter.hbs'

function getCount(el) {
  const total = el.value.length
  const max = parseInt(el.attributes.maxlength.value, 10)

  return max - total
}

function createLabel(el) {
  const content = tmpl({
    id:      el.id,
    content: getCount(el),
  })
  const parent = document.createElement('div')
  parent.innerHTML = content

  return parent.childNodes[0]
}

function updateCounter(label, remaining) {
  label.innerHTML = remaining
}

function initCounter(el) {
  const parent = el.parentElement
  const label = createLabel(el)
  parent.insertBefore(label, el.nextSibling)

  el.addEventListener('input', (e) => {
    const remaining = getCount(e.target)
    updateCounter(label, remaining)
  }, false)
}

export function init(sel = '[data-character-counter]') {
  const inputs = Array.prototype.slice.call(document.querySelectorAll(sel))

  inputs.forEach(initCounter)
}
