import { ReglesOptionnelles } from "./settings/regles-optionnelles.js";

export class RdDConfirm {
  static confirmer(options, autresActions) {
    if (options.settingConfirmer && !ReglesOptionnelles.isSet(options.settingConfirmer)) {
      return options.onAction()
    }
    let btns = [
      RdDConfirm._createButtonAction(options),
      RdDConfirm._createButtonCancel()
    ];
    if (options.settingConfirmer) {
      btns = [RdDConfirm._createButtonActionSave(options), ...btns];
    }
    if (autresActions) {
      const extras = Object.values(autresActions).map(b => {
        if (b.icon && b.icon.includes('<')) b.icon = RdDConfirm._normalizeIcon(b.icon);
        return b;
      });
      btns = [...extras, ...btns];
    }
    new foundry.applications.api.DialogV2({
      title: options.title,
      content: options.content,
      buttons: btns,
      position: { width: 150 * btns.length }
    }).render({ force: true });
  }

  static _createButtonCancel() {
    return { action: "cancel", label: "Annuler", icon: "fa-solid fa-times" };
  }

  static _createButtonAction(options) {
    return {
      action: "action",
      label: options.buttonLabel,
      icon: "fa-solid fa-check",
      callback: () => options.onAction()
    };
  }

  static _normalizeIcon(html) {
    const m = html.match(/class=["']([^"']+)["']/);
    return m ? m[1] : html;
  }

  static _createButtonActionSave(options) {
    return {
      action: "actionSave",
      label: options.buttonLabel + " et ne plus demander",
      icon: "fa-solid fa-user-check",
      callback: () => {
        ReglesOptionnelles.set(options.settingConfirmer, false);
        options.onAction();
      }
    };
  }
}
