import { DIFF, DIFFS, ROLL_TYPE_CUISINE, ROLL_TYPE_MEDITATION, ROLL_TYPE_OEUVRE, ROLL_TYPE_SORT, ROLL_TYPE_TACHE } from "./roll-constants.mjs";
import { ROLLDIALOG_SECTION, RollPart } from "./roll-part.mjs";
import { Misc } from "../misc.js";

export const PART_DIFF = "diff"

const EXCLUDED_ROLL_TYPES = [
  ROLL_TYPE_TACHE,
  ROLL_TYPE_MEDITATION,
  ROLL_TYPE_SORT,
  ROLL_TYPE_CUISINE,
  ROLL_TYPE_OEUVRE]

export class RollPartDiff extends RollPart {

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

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

  store(rollData, targetData) {
    const current = this.getCurrent(rollData)
    this.setSaved(targetData, {
      value: current.value,
      type: current.type
    })
  }

  visible(rollData) {
    if (EXCLUDED_ROLL_TYPES.includes(rollData.type.current) || rollData.type.appreciation) {
      return false
    }
    const current = this.getCurrent(rollData)
    /* TODO: affiner les cas où afficher ou non. devrait s'afficher pour les jets basiques (même si pas d'opposant sélectionné)*/
    return (DIFF.AUCUN !=current.type) && Object.values(DIFF).includes(current.type)
  }

  prepareContext(rollData) {
    const current = this.getCurrent(rollData)
    const diffType = DIFFS[current.type] ?? DIFFS[DIFF.AUCUN]
    const min = -10
    const max = diffType.max
    const value = Misc.inRange(current.value ?? 0, min, max)
    foundry.utils.mergeObject(current,
      {
        type: diffType.key,
        label: diffType?.label ?? '',
        disabled: !diffType.libre,
        value,
        min,
        max
      },
      { inplace: true }
    )
    current.diffOptions = Array.from(
      { length: max - min + 1 },
      (_, i) => ({ value: min + i, label: String(min + i) })
    )
  }

  setDiff(rollData, diff) {
    const current = this.getCurrent(rollData)
    current.value = diff.diff ?? current.value
    current.type = diff.type ?? current.type
  }

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

  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))
  }

}