import "../xregexp-all.js";
import { TextRollManager } from "./text-roll-formatter.js";

const REGEXP_ROLL_FORMULA = "(?<formula>[^\\[\\]]+)"
const XREGEXP_ROLL_FORMULA = XRegExp("@roll\\[" + REGEXP_ROLL_FORMULA + "\\]", 'giu')

/**
 * classe pour gérer les jets de dés (formules Foundry)
 */
export class TextRollFormula {
  get code() { return 'formula' }
  get template() { return `systems/foundryvtt-reve-de-dragon/templates/apps/textroll/link-text-roll-formula.hbs` }

  async onReplaceRoll(context) {
    const handler = new FormulaTextBuilder(context)
    return await handler.replaceAll()
  }

  async onRollText(event, actor) {
    const node = TextRollManager.getNode(event)
    const rollFormula = node.data('formula')
    if (rollFormula) {
      const roll = new Roll(rollFormula)
      await roll.evaluate()
      await roll.toMessage()
    }
  }
}

class FormulaTextBuilder {
  constructor(context) {
    this.context = context
  }

  async replaceAll() {
    await XRegExp.forEach(this.context.text, XREGEXP_ROLL_FORMULA,
      async (rollMatch, i) => await this.replaceMatch(rollMatch, i))
    return this.context.text
  }

  async replaceMatch(rollMatch, i) {
    if (rollMatch.formula) {
      const replacement = await TextRollManager.createRollText(this.context,
        {
          code: this.context.code,
          formula: rollMatch.formula,
        })
      this.context.text = this.context.text.replace(rollMatch[0], replacement)
    }
  }
}
