import { RdDCarac } from "../rdd-carac.js"
import { RollPartSelect } from "./roll-part-select.mjs"
import { ROLLDIALOG_SECTION, RollPart } from "./roll-part.mjs"

const COEUR = "coeur"

const SANS_AMOUR = { key: '', label: "", value: 0 }

export class RollPartCoeur extends RollPartSelect {

  get code() { return COEUR }
  get section() { return ROLLDIALOG_SECTION.CONDITIONS }

  get useCheckboxTemplate() { return false }

  isValid(rollData) { return rollData.active.actor.isPersonnage() }
  visible(rollData) {
    return this.getRefs(rollData).amoureux.length > 1 && RdDCarac.isVolonte(rollData.current.carac.key)
  }

  loadRefs(rollData) {
    const liste = rollData.active.actor.listeAmoureux()
      .filter(amour => amour.coeur > 0)
      .map(RollPartCoeur.$extractAmoureux)

    this.getRefs(rollData).amoureux = [SANS_AMOUR, ...liste]
    this.$selectAmoureux(rollData)
  }

  choices(refs) { return refs.amoureux }

  static $extractAmoureux(amour) {
    return {
      key: amour.id,
      label: amour.name,
      value: -2 * (amour?.coeur ?? 0),
      amour: amour
    }
  }

  $selectAmoureux(rollData, key) {
    this.selectByKey(rollData, key, 0)
  }

  getAjustements(rollData) {
    const current = this.getCurrent(rollData)
    if (current.key != '') {
      return [{
        label: "Coeur pour " + current.label,
        value: current.value
      }]
    }
    return []
  }

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

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