import { helper } from "@ember/component/helper"
import { htmlSafe } from "@ember/string"
import { isEmpty } from "@ember/utils"

export function highlight(_, hash) {
  let text = hash.phrase
  let part = hash.part

  if (isEmpty(part)) return text

  let words = text.split(" ")
  let parts = part.split(" ")

  let highlightedWords = words.map(word => {
    let next = {
      highlighted: false,
      word
    }

    parts.forEach(part => {
      if (next.highlighted) return

      let { word } = next

      next.word = word.replace(
        new RegExp(part, "ig"),
        '<mark class="en-select-option-highlight">$&</mark>'
      )

      if (word !== next.word) {
        next.highlighted = true
      }
    })

    return next
  })

  return htmlSafe(
    highlightedWords
      .map(word => word.word)
      .join(" ")
  )
}

export default helper(highlight)
