import { ROLLDIALOG_SECTION, RollPart } from "./roll-part.mjs"

export class RollPartCheckbox extends RollPart {

  get section() { return ROLLDIALOG_SECTION.CONDITIONS }

  get useCheckboxTemplate() { return true }
  get template() { return this.useCheckboxTemplate ? 'systems/foundryvtt-reve-de-dragon/templates/roll/roll-part-checkbox.hbs' : super.template }
  get isDefaultChecked() { return true }

  restore(rollData) {
    const checked = this.getSaved(rollData).checked
    this.getCurrent(rollData).checked = checked == undefined? this.isDefaultChecked : checked
  }

  store(rollData, targetData) {
    this.setSaved(targetData, { checked: this.getCurrent(rollData).checked })
  }

  loadRefs(rollData) {
    const refs = this.getRefs(rollData)
    refs.label = this.getCheckboxLabel(rollData)
  }

  prepareContext(rollData) {
    const current = this.getCurrent(rollData)
    if (current.checked == undefined) {
      /* TODO: user setting? */
      current.checked = true
    }
    current.value = this.getCheckboxValue(rollData)
    current.icon = this.getCheckboxIcon(rollData)
  }

  getAjustements(rollData) {
    const current = this.getCurrent(rollData)
    if (current.checked) {
      return [{ label: this.getCheckboxLabelAjustement(rollData), value: current.value }]
    }
    return []
  }

  getCheckboxLabelAjustement(rollData) {
    return `${this.getCheckboxIcon(rollData)} ${this.getCheckboxLabel(rollData)}`
  }

  async _onRender(rollDialog, context, options) {
    const checkbox = rollDialog.element.querySelector(`roll-section[name="${this.code}"] input[name="${this.code}"]`)
    
    checkbox?.addEventListener("change", e => {
      this.getCurrent(rollDialog.rollData).checked = e.currentTarget.checked
      rollDialog.render()
    })
  }

  getCheckboxIcon(rollData) { return '' }
  getCheckboxLabel(rollData) { return "LABEL" }
  getCheckboxValue(rollData) { return 0 }
}
