Source: lib/normalize.js

const { listeMax, listeNbDefault } = require('./config')
const { toAscii } = require('sesajstools')

/**
 * Retourne values purgé de null|undefined si c'est un tableau non vide, null sinon
 * @param {Array} values
 * @return {null|Array}
 */
function basicArrayIndexer (values) {
  if (Array.isArray(values)) {
    values = values.filter(elt => elt !== undefined && elt !== null)
    if (values.length) return values
  }
  return null
}

/**
 * Normalise {skip, limit} et le retourne
 * @param {Object} [options]
 * @param {number} [options.limit]
 * @param {number} [options.skip]
 * @return {{limit: number, skip: number}}
 */
function getNormalizedGrabOptions (options) {
  if (!options || typeof options !== 'object') return { limit: listeNbDefault, skip: 0 }
  const grabOptions = {}
  // on peut nous passer des strings
  const limit = Number(options.limit)
  const skip = Number(options.skip)

  grabOptions.limit = (Number.isInteger(limit) && limit > 0 && limit < listeMax) ? limit : listeNbDefault
  grabOptions.skip = (Number.isInteger(skip) && skip >= 0) ? skip : 0

  return grabOptions
}

/**
 * Callback de normalisation de string (utilisé pour l'index du nom d'un groupe)
 * @param {string} nom
 * @param {boolean} [strict=true] passer false pour renvoyer une chaîne vide plutôt que throw en cas de nom invalide
 * @return {string} Le nom sans caractères autres que [a-z0-9]
 * @throws {Error} si strict et nom invalide (pas une string ou retournerait une chaîne vide après normalisation)
 */
function getNormalizedName (nom, strict = true) {
  // on peut être appelé avec null (sortie de basicArrayIndexer)
  if (nom === null) return null
  if (!nom || typeof nom !== 'string' || nom === 'undefined') {
    if (strict) throw Error('nom invalide')
    else return ''
  }
  const cleaned = toAscii(nom.toLowerCase()) // minuscules sans accents
    .replace(/[^a-z0-9]/g, ' ') // sans caractères autres que a-z0-9
    .replace(/  +/g, ' ').trim() // on vire les espaces en double + les éventuels de début et fin
  if (cleaned) return cleaned
  if (strict) throw Error(`nom ${nom} invalide`)
  return ''
}

module.exports = {
  basicArrayIndexer,
  getNormalizedGrabOptions,
  getNormalizedName
}