import { MatchDecorator, Decoration } from '@codemirror/view'
import type { Suggestion } from './types.js'
import { ChipWidget } from './PlaceholderWidget.js'

/**
 * A class that specializes in creating and managing decorations for suggestion matches in a code editor.
 */
export class SuggestionMatchDecorator extends MatchDecorator {
  /**
   * Creates a new instance of SuggestionMatchDecorator.
   * @param regexp - The regular expression used to match suggestions in the code.
   * @param suggestions - An array of suggestions that will be used to create decorations.
   * Each suggestion should have a unique `id` and a `label` that will be displayed in the editor.
   */
  constructor(
    regexp: RegExp,
    public suggestions: Suggestion[]
  ) {
    super({
      regexp,
      decoration: (match) => this.#decoration(match),
    })
  }

  #decoration(match: RegExpExecArray): Decoration {
    const label = match[1]
    const suggestion = this.suggestions.find((s) => s.label === label)

    // If no suggestion is found, create a default one
    const suggestionData: Suggestion = suggestion || { id: label, label }

    return Decoration.replace({
      widget: new ChipWidget(suggestionData),
    })
  }
}
