import "./xregexp-all.js";
import { SystemCompendiums } from "../settings/system-compendiums.js";
import { ACTOR_TYPES } from "../constants.js";
import { TextRollAlchimie } from "./textroll/text-roll-alchimie.js";
import { TextRollCaracCompetence } from "./textroll/text-roll-carac-competence.js";
import { TextRollFormula } from "./textroll/text-roll-formula.js";
import { TextRollManager } from "./textroll/text-roll-formatter.js";

const TEXT_ROLL_MANAGERS = [
  new TextRollAlchimie(),
  new TextRollCaracCompetence(),
  new TextRollFormula()]

export class RdDTextEditor {
  static registerChatCallbacks(html) {
    html.on("click", '.roll-text', async event => await RdDTextEditor.rollText(event))
  }

  static async enrichHTML(text, object, options = {showlink:true}) {
    const context = {
      text,
      object,
      options,
      competences: await SystemCompendiums.getCompetences(ACTOR_TYPES.personnage),
    }

    for (let manager of TEXT_ROLL_MANAGERS) {
      context.code = manager.code
      context.template = manager.template
      context.text = await manager.onReplaceRoll(context);
    }

    return await TextEditor.enrichHTML(context.text, {
      relativeTo: object,
      secrets: object?.isOwner,
      async: true
    })
  }

  static async _applyReplaceAll(manager, context) {
    context.code = manager.code
    context.template = manager.template
    context.text = await manager.onReplaceRoll(context);
    return context.text
  }

  static getEventElement(event) {
    return $(event.currentTarget)?.parents(".roll-text-link");
  }

  static async rollText(event, actor) {
    const code = TextRollManager.getNode(event)?.data('code')
    const manager = TEXT_ROLL_MANAGERS.find(it => it.code == code)
    if (manager) {
      await manager.onRollText(event, actor)
    }
  }

  static async chatRollText(event) {
    const node = TextRollManager.getNode(event);
    if (node) {
      const code = node.data('code')
      const param = node.data('json')
      const manager = TEXT_ROLL_MANAGERS.find(it => it.code == code)

      const text = await TextRollManager.createRollText(
        {
          code,
          template: manager.template,
          options: { showLink: false }
        },
        param)
      ChatMessage.create({
        content: text
      })
    }
  }
}