import "../xregexp-all.js";
import { ACTOR_TYPES, ITEM_TYPES } from "../../constants.js";
import { RdDCarac } from "../../rdd-carac.js";
import { RdDUtility } from "../../rdd-utility.js";
import { RdDAlchimie } from "../../rdd-alchimie.js";
import { TextRollManager } from "./text-roll-formatter.js";

const REGEX_ALCHIMIE_TERMES = "(?<termes>(\\w|-)+)"
const REGEX_ALCHIMIE_MANIP = "(?<manip>(couleur|consistance))"
const XREGEXP_ROLL_ALCHIMIE = XRegExp("@roll\\[" + REGEX_ALCHIMIE_MANIP + "\\s+" + REGEX_ALCHIMIE_TERMES + "\\]", 'giu')
const XREGEXP_ROLL_ALCHIMIE_MANIP = XRegExp("@" + REGEX_ALCHIMIE_MANIP + "\\{" + REGEX_ALCHIMIE_TERMES + "\\}", 'giu')

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

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

  async onRollText(event, actor) {
    actor = this.getSelectedActor(actor)
    if (actor) {
      const node = TextRollManager.getNode(event)
      const recetteId = node.data('recetteid')
      const manip = node.data('manip')
      const termes = node.data('termes')
      if (recetteId) {
        await actor.effectuerTacheAlchimie(recetteId, manip, termes)
      }
      else {
        const carac = RdDCarac.caracDetails(RdDAlchimie.getCaracTache(manip))
        const diff = RdDAlchimie.getDifficulte(termes)
        await actor.rollCaracCompetence(carac.code, 'Alchimie', diff)
      }
    }
  }

  getSelectedActor(actor) {
    actor = actor ?? RdDUtility.getSelectedActor()
    if (actor && actor.type == ACTOR_TYPES.personnage) {
      return actor
    }
    return undefined
  }
}

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

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

  async replaceMatch(rollMatch, i) {
    if (rollMatch.termes && rollMatch.manip) {
      const manip = rollMatch.manip
      const termes = rollMatch.termes
      const carac = RdDCarac.caracDetails(RdDAlchimie.getCaracTache(manip))
      const diff = RdDAlchimie.getDifficulte(termes)
      const recette = (this.context.object instanceof Item && this.context.object.type == ITEM_TYPES.recettealchimique) ? this.context.object : undefined
      const replacement = await TextRollManager.createRollText(this.context,
        {
          code: this.context.code,
          manip, termes, carac, diff, recetteid: recette?.id,
        })
      this.context.text = this.context.text.replace(rollMatch[0], replacement);
    }
  }
}