import slugify from 'slugify'

export const getAlias = (artistes, priorite = null, enhanced = false) => {
  const safeArtistes = artistes || []

  if (safeArtistes.length === 1 && !enhanced) {
    return safeArtistes[0].alias
  }

  if (safeArtistes.length === 1 && enhanced) {
    return [{
      type: 'element',
      value: safeArtistes[0].alias
    }]
  }

  const alias = []
  const splittedPriority = priorite ? priorite.split('-')
    .map(p => Number.parseInt(p, 10)) : null

  if (splittedPriority) {
    for (const element of splittedPriority) {
      const foundedArtistes = safeArtistes.find(({id}) => id === element)
      if (foundedArtistes) {
        alias.push(foundedArtistes.alias)
      }
    }
  } else {
    for (const artiste of safeArtistes) {
      alias.push(artiste.alias)
    }
  }

  if (enhanced) {
    const list = new Intl.ListFormat('fr').formatToParts(alias)
    return list
  }

  return new Intl.ListFormat('fr').format(alias)
}

function separateString(inputString) {
  const regex = /\s*,\s*|\s+et\s+/
  const strings = inputString.split(regex).map(element => element.trim())
  return strings
}

export const getAliasObject = inputString => {
  const awtis = separateString(inputString)

  return awtis.map(alias => ({
    alias,
    slug: slugify(alias, {lower: true, remove: /[*#+~.()'"!:@]/g})
  }))
}
