const helperKeys = [
  'getResponseBufferHint',
  'inspectReceivedBytes',
  'parseSendExpected',
  'readResponseFromBuffer'
]

function createEmptyHelpers() {
  return helperKeys.reduce((result, key) => {
    result[key] = null
    return result
  }, {})
}

function normalizeHelpers(helpers = {}) {
  const normalized = {}

  helperKeys.forEach((key) => {
    normalized[key] = typeof helpers[key] === 'function' ? helpers[key] : null
  })

  return normalized
}

function createProtocolHelperRegistry() {
  let helpers = createEmptyHelpers()
  let helpersLoaded = false
  let helpersLoader = null

  function ensureLoaded() {
    if (helpersLoaded || typeof helpersLoader !== 'function') return

    helpersLoaded = true
    helpers = normalizeHelpers(helpersLoader() || {})
  }

  function configure(nextHelpers = {}) {
    if (typeof nextHelpers === 'function') {
      helpersLoader = nextHelpers
      helpersLoaded = false
      helpers = createEmptyHelpers()
      return
    }

    helpersLoader = null
    helpersLoaded = true
    helpers = normalizeHelpers(nextHelpers)
  }

  function get(key) {
    ensureLoaded()

    return helpers[key] || null
  }

  function getHelpers() {
    ensureLoaded()

    return {
      ...helpers
    }
  }

  return {
    configure,
    get,
    getHelpers
  }
}

module.exports = {
  createProtocolHelperRegistry
}
