import { renderTemplate } from "./constants.js"
import { Misc } from "./misc.js"
import { RdDResolutionTable } from "./rdd-resolution-table.js"
import { RdDRollResult } from "./rdd-roll-result.js"

const titleTableDeResolution = "Table de résolution"

export class RdDRollResolutionTable extends foundry.applications.api.DialogV2 {
  static resolutionTable = undefined

  static async open() {
    if (RdDRollResolutionTable.resolutionTable == undefined) {
      const rollData = {}
      RdDRollResolutionTable._setDefaultOptions(rollData)
      const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-roll-resolution.hbs", rollData)
      RdDRollResolutionTable.resolutionTable = new RdDRollResolutionTable(rollData, content)
      RdDRollResolutionTable.resolutionTable.render({ force: true })
    }
    else {
      RdDRollResolutionTable.resolutionTable.bringToFront()
    }
  }

  static _setDefaultOptions(rollData) {
    let defRollData = {
      show: { title: titleTableDeResolution },
      ajustementsConditions: CONFIG.RDD.ajustementsConditions,
      difficultesLibres: CONFIG.RDD.ajustementsConditions,
      etat: 0, moral: 0, carac: {}, finalLevel: 0, diffConditions: 0, diffLibre: 0,
      use: { conditions: true, libre: true }
    }
    foundry.utils.mergeObject(rollData, defRollData, { overwrite: false })
    for (let i = 1; i < 21; i++) {
      const key = `${i}`
      rollData.carac[key] = { type: "number", value: i, label: key }
    }
    let selected = (rollData.selectedCarac && rollData.selectedCarac.label)
      ? rollData.selectedCarac.label
      : (Number.isInteger(rollData.selectedCarac))
        ? rollData.selectedCarac
        : 10
    rollData.selectedCarac = rollData.carac[selected]
  }

  constructor(rollData, content) {
    super({
      title: titleTableDeResolution,
      content,
      classes: ["rdd-roll-dialog"],
      position: { top: 50, width: 'fit-content', height: 'fit-content' },
      buttons: [
        { label: "Lancer les dés et fermer", action: "lancer-fermer", callback: () => this.onLancerFermer() }
      ]
    })
    this.rollData = rollData
  }

  _onRender(context) {
    super._onRender(context)
    this.bringToFront()
    const el = this.element
    const dl = el.querySelector("[name='diffLibre']")
    if (dl) dl.value = Misc.toInt(this.rollData.diffLibre)
    const dc = el.querySelector("[name='diffConditions']")
    if (dc) dc.value = Misc.toInt(this.rollData.diffConditions)
    this.updateRollResult()
    el.querySelector(".lancer-table-resolution")?.addEventListener("click", () => this.onLancer())
    el.querySelector("[name='diffLibre']")?.addEventListener("change", event => {
      this.rollData.diffLibre = Misc.toInt(event.currentTarget.value)
      this.updateRollResult()
    })
    el.querySelector("[name='diffConditions']")?.addEventListener("change", event => {
      this.rollData.diffConditions = Misc.toInt(event.currentTarget.value)
      this.updateRollResult()
    })
    el.querySelector("[name='carac']")?.addEventListener("change", event => {
      this.rollData.selectedCarac = this.rollData.carac[event.currentTarget.value]
      this.updateRollResult()
    })
  }

  async onLancer() {
    await RdDResolutionTable.rollData(this.rollData)
    console.log("RdDRollResolutionTable -=>", this.rollData, this.rollData.rolled)
    await RdDRollResult.displayRollData(this.rollData)
  }

  async onLancerFermer() {
    await RdDResolutionTable.rollData(this.rollData)
    console.log("RdDRollResolutionTable -=>", this.rollData, this.rollData.rolled)
    await RdDRollResult.displayRollData(this.rollData)
  }

  async updateRollResult() {
    let rollData = this.rollData
    rollData.caracValue = parseInt(rollData.selectedCarac.value)
    rollData.finalLevel = Misc.toInt(rollData.diffConditions) + Misc.toInt(rollData.diffLibre)
    const htmlTable = await RdDResolutionTable.buildHTMLTable({
      carac: rollData.caracValue, level: rollData.finalLevel, maxCarac: 20, maxLevel: 10
    })
    const el = this.element
    const carac = el.querySelector("[name='carac']")
    if (carac) carac.value = rollData.caracValue
    const part = el.querySelector(".roll-part-resolution")
    if (part) part.textContent = rollData.selectedCarac.value + " / " + Misc.toSignedString(rollData.finalLevel)
    const placeholder = el.querySelector("div.placeholder-resolution")
    if (placeholder) placeholder.innerHTML = htmlTable
  }

  async close() {
    await super.close()
    RdDRollResolutionTable.resolutionTable = undefined
  }
}
