import { EcrymeUtility } from "../common/ecryme-utility.js";
import { EcrymeConfrontDialog } from "./ecryme-confront-dialog.js";

const { HandlebarsApplicationMixin } = foundry.applications.api

/**
 * Confrontation start dialog — Application V2 version.
 * Player picks which dice formula to roll (normal / spleen / ideal),
 * the dice are rolled and the main EcrymeConfrontDialog is opened.
 */
export class EcrymeConfrontStartDialog extends HandlebarsApplicationMixin(foundry.applications.api.ApplicationV2) {

  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-ecryme", "ecryme-confront-start-dialog"],
    position: { width: 540 },
    window: { title: "ECRY.ui.confront" },
    actions: {
      rollNormal: EcrymeConfrontStartDialog.#onRollNormal,
      rollSpleen: EcrymeConfrontStartDialog.#onRollSpleen,
      rollIdeal:  EcrymeConfrontStartDialog.#onRollIdeal,
      cancel:     EcrymeConfrontStartDialog.#onCancel,
    },
  }

  /** @override */
  static PARTS = {
    content: { template: "systems/fvtt-ecryme/templates/dialogs/confront-start-dialog.hbs" },
  }

  /* -------------------------------------------- */
  constructor(actor, rollData, options = {}) {
    super(options)
    this.actor    = actor?.token?.actor ?? actor
    this.rollData = rollData
  }

  /* -------------------------------------------- */
  static async create(actor, rollData) {
    if (!actor)    throw new Error("Ecryme | No actor provided for confront dialog")
    if (!rollData) throw new Error("Ecryme | No roll data provided for confront dialog")
    if (actor?.token) rollData.tokenId = actor.token.id
    return new EcrymeConfrontStartDialog(actor, rollData)
  }

  /* -------------------------------------------- */
  async _prepareContext() {
    return {
      ...this.rollData,
      config: game.ecryme.config,
    }
  }

  /* -------------------------------------------- */
  async #rollConfront(diceFormula) {
    const myRoll = await new Roll(diceFormula).roll()
    await EcrymeUtility.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))

    const rollData = this.rollData
    rollData.roll = foundry.utils.deepClone(myRoll)
    rollData.availableDices = []
    for (const result of myRoll.terms[0].results) {
      if (!result.discarded) {
        const dup = foundry.utils.deepClone(result)
        dup.location = "mainpool"
        rollData.availableDices.push(dup)
      }
    }

    const confrontDialog = await EcrymeConfrontDialog.create(this.actor, rollData)
    confrontDialog.render(true)
    this.close()
  }

  /* -------------------------------------------- */
  static async #onRollNormal(event, target) { await this.#rollConfront("4d6")     }
  static async #onRollSpleen(event, target) { await this.#rollConfront("5d6kl4")  }
  static async #onRollIdeal(event, target)  { await this.#rollConfront("5d6kh4")  }
  static        #onCancel(event, target)    { this.close()                         }
}
