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

const ROLLMODE = "rollmode"

export class RollPartRollMode extends RollPart {

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

  loadRefs(rollData) {
    const refs = this.getRefs(rollData)
    refs.rollmodes = Object.entries(CONFIG.ChatMessage.modes).map(([k, v]) => { return { key: k, label: v.label, icon: v.icon } })
  }

  restore(rollData) {
    this.setCurrent(rollData, { key: this.getSaved(rollData)?.key ?? game.settings.get("core", "messageMode") })
  }

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

  async _onRender(rollDialog, context, options) {
    const rollvisibilityButtons = rollDialog.element.querySelectorAll(`button[name="roll-rollmode"]`)
    rollvisibilityButtons?.forEach(it => it.addEventListener(
      "click", e => {
        e.preventDefault()
        this.getCurrent(rollDialog.rollData).key = e.currentTarget.dataset.key
        rollDialog.render()
      }))
  }

  getHooks(rollDialog) {
    return [
      { hook: "clientSettingChanged", fn: (setting, update, options, id) => this.onUpdateSetting(rollDialog, setting, update, options, id) },
    ]
  }

  async onUpdateSetting(rollDialog, setting, update, options, id) {
    if (setting == 'core.messageMode') {
      this.setCurrent(rollDialog.rollData, { key: game.settings.get("core", "messageMode") })
      rollDialog.render()
    }
  }
}
