import { SYSTEM_RDD } from "../constants.js";
import { Misc } from "../misc.js";
import { ROLLDIALOG_SECTION, RollPart } from "./roll-part.mjs";

const CONDITIONS = "conditions"
const DESCR_CONDITIONS = "Conditions"

export class RollPartConditions extends RollPart {
  /** TODO: use alternate to numberInput that supports displaying '+' sign */
  settingMin() { return RollPart.settingKey(this, 'min') }
  settingMax() { return RollPart.settingKey(this, 'max') }

 visible(rollData) {
    const current = this.getCurrent(rollData)
    return !current.hide
  }

  onReady(rollParts) {
    game.settings.register(SYSTEM_RDD, this.settingMin(),
      {
        name: "Malus maximal de conditions",
        type: Number,
        config: true,
        scope: "world",
        range: { min: -20, max: -10, step: 1 },
        default: -16
      }
    )
    game.settings.register(SYSTEM_RDD, this.settingMax(),
      {
        name: "Bonus maximal de conditions",
        type: Number,
        config: true,
        scope: "world",
        range: { min: 5, max: 15, step: 1 },
        default: 10
      }
    )
  }

  restore(rollData) {
    const current = this.getCurrent(rollData)
    current.value = this.getSaved(rollData)?.value ?? current.value ?? 0
    current.hide = this.getSaved(rollData)?.hide
  }


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

  /** @override */
  get code() { return CONDITIONS }
  get section() { return ROLLDIALOG_SECTION.CONDITIONS }

  prepareContext(rollData) {
    const current = this.getCurrent(rollData)
    const min = game.settings.get(SYSTEM_RDD, this.settingMin())
    const max = game.settings.get(SYSTEM_RDD, this.settingMax())
    current.min = min
    current.max = max
    current.value = Misc.inRange(current.value ?? 0, min, max)
    current.conditionOptions = Array.from(
      { length: max - min + 1 },
      (_, i) => ({ value: min + i, label: String(min + i >= 0 ? `+${min + i}` : min + i) })
    )
  }

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

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

    select?.addEventListener("change", e => this.onNumericInputChange(e, rollDialog))
  }

}