import { Grammar } from "../grammar.js"
import { RollPartSelect } from "./roll-part-select.mjs"
import { ROLLDIALOG_SECTION } from "./roll-part.mjs"

export const PART_CARAC = "carac"

export class RollPartCarac extends RollPartSelect {
  /** TODO: remplacer selectOption par une sorte de sélecteur plus sympa? */

  get code() { return PART_CARAC }
  get name() { return 'Caractéristiques' }
  get section() { return ROLLDIALOG_SECTION.CARAC }

  loadRefs(rollData) {
    const refs = this.getRefs(rollData)
    const selected = this.getSelected(rollData)
    const actor = rollData.active.actor
    refs.all = [...this.$getActorCaracs(actor), ...this.$getCaracCompetenceCreature(actor)]
    if (selected.forced && selected.key) {
      refs.all = refs.all.filter(c => c.key == selected.key || Grammar.includesLowerCaseNoAccent(c.label, selected.key))
    }
    refs.caracs = refs.all
    this.$selectCarac(rollData)
  }

  choices(refs) { return refs.caracs }

  $getActorCaracs(actor) {
    return Object.entries(actor.getCarac())
      .filter(([key, c]) => key != 'taille')
      .map(([key, carac]) => {
        return RollPartCarac.$extractCarac(key, carac)
      })
  }

  $getCaracCompetenceCreature(actor) {
    if (actor.isPersonnage()) {
      return []
    }
    return actor.getCompetences()
      .map(it => { return { key: it.name, label: it.name, value: parseInt(it.system.carac_value) } })
  }

  static $extractCarac(key, carac) {
    return {
      key: key,
      label: carac.label,
      value: parseInt(carac.value)
    }
  }

  filterCaracs(rollData, allowed = []) {
    allowed = allowed.filter(it => it != undefined)
    const refs = this.getRefs(rollData)
    refs.caracs = allowed.length > 0
      ? refs.all.filter(it => allowed.includes(it.key))
      : refs.all
    this.$selectCarac(rollData)
  }

  prepareContext(rollData) {
    this.$selectCarac(rollData)
  }

  getAjustements(rollData) {
    return []
  }

  async _onRender(rollDialog, context, options) {
    const select = rollDialog.element.querySelector(`roll-section[name="${this.code}"] select`)

    select?.addEventListener("change", async e => {
      const selectOptions = e.currentTarget.options
      const index = selectOptions.selectedIndex
      this.$selectCarac(rollDialog.rollData, selectOptions[index]?.value)
      rollDialog.render()
    })
  }

  $selectCarac(rollData, key) {
    this.selectByKey(rollData, key, 10)
  }
}
