import { Callable, Callable1, LineEdit, Variant } from 'godot'
import { export_, onready } from 'godot.annotations'

export default class AutocompleteLine extends LineEdit {
  @export_(Variant.Type.TYPE_BOOL)
  private auto_suggest: boolean = true

  @onready("SuggestionLine")
  private suggestion!: LineEdit

  autocomplete_list: string[] = []
  last_autocomplete: number = -1

  _on_text_changed!: Callable1<string>

  _ready(): void {
    this._on_text_changed = Callable.create(this, this.suggest)

    if (this.auto_suggest) {
      this.text_changed.connect(this._on_text_changed)
    }
  }

  suggest(value: string): boolean {
    const item = this.fuzzy_find(value)

    if (item > -1) {
      this.suggestion.text = this.autocomplete_list[item]
      return true
    }

    return false
  }

  autocomplete(value?: string) {
    this.text = value || this.suggestion.text
    this.suggestion.clear()
  }

  fuzzy_find(value: string): number {
    return this.autocomplete_list.findIndex(text => text.startsWith(value))
  }
}
