import { RDD_CONFIG } from "../constants.js"
import { RdDItemCompetence } from "../item-competence.js"
import { RdDCarac } from "../rdd-carac.js"
import { RollPartCheckbox } from "./roll-part-checkbox.mjs"

const ENCTOTAL = "enctotal"

export class RollPartEncTotal extends RollPartCheckbox {

  get code() { return ENCTOTAL }
  get useCheckboxTemplate() { return false }

  visible(rollData) {
    return RdDCarac.isAgiliteOuDerobee(rollData.current.carac.key)
      && RdDItemCompetence.isMalusEncombrementTotal(rollData.current.comp?.key)
  }

  loadRefs(rollData) {
    const refs = this.getRefs(rollData)
    refs.malusEnc = - Math.floor(rollData.active.actor.getEncTotal())
    const current = this.getCurrent(rollData)
    current.value = refs.malusEnc
    current.encOptions = Array.from(
      { length: 31 },
      (_, i) => ({ value: -30 + i, label: String(-30 + i) })
    )
  }

  async _onRender(rollDialog, context, options) {
    super._onRender(rollDialog, context, options)

    const inputMalusEnc = rollDialog.element.querySelector(`roll-section[name="${this.code}"] [name="malusenc"]`)

    inputMalusEnc?.addEventListener("change", e => {
      const malusEnc = Math.floor(e.currentTarget.value)
      const rollData = rollDialog.rollData
      const refs = this.getRefs(rollData)
      const current = this.getCurrent(rollData)
      if (refs.malusEnc == current.value) {
        current.value = malusEnc
      }
      refs.malusEnc = malusEnc
      rollDialog.render()
    })
  }

  getCheckboxIcon(rollData) { return `<img src="${RDD_CONFIG.icons.surenc}">` }
  getCheckboxLabel(rollData) { return "Enc. total" }
  getCheckboxValue(rollData) { return this.getCurrent(rollData).value }
}
