import { TeDeumUtility } from "../common/tedeum-utility.js";

/* -------------------------------------------- */
export class TeDeumCombat extends Combat {

  /* -------------------------------------------- */
  async rollInitiative(ids, formula = undefined, messageOptions = {}) {
    //console.log("Roll INIT !")
    ids = typeof ids === "string" ? [ids] : ids;
    for (let cId of ids) {
      const c = this.combatants.get(cId);
      let initBonus = c.actor ? c.actor.getInitiativeScore(this.id, cId) : -1;
      console.log("Init Bonus : ", c.name, initBonus)
      await this.updateEmbeddedDocuments("Combatant", [{ _id: cId, initiative: initBonus }]);
    }

    return this;
  }

  /* -------------------------------------------- */
  async modifyAction(combatantId, delta, isMainGauche = false) {
    let combatant = this.combatants.get(combatantId)
    if (!combatant) return;
    let ca = combatant.getFlag("world", "available-actions")
    if (!ca) {
      ca = { nbActions: 1, nbActionsMainGauche: 0 }
    }
    if (isMainGauche) {
      ca.nbActionsMainGauche += delta
    } else {
      ca.nbActions += delta
    }
    if (ca.nbActionsMainGauche < 0) ca.nbActionsMainGauche = 0
    if (ca.nbActions < 0) ca.nbActions = 0
    console.log("Modify Action : ", combatant.name, ca)
    if (game.user.isGM) {
      await TeDeumUtility.updateCombatantActions(combatant, ca)
    } else {
      game.socket.emit("system.fvtt-te-deum", { msg: "msg_modify_combat_action", data: { combatantId: combatantId, ca: ca } })
    }
  }

  /* -------------------------------------------- */
  static async checkTurnPosition() {
    while (game.combat.turn > 0) {
      await game.combat.previousTurn()
    }
  }

  /* -------------------------------------------- */
  _onDelete() {
    let combatants = this.combatants.contents
    for (let c of combatants) {
      let actor = game.actors.get(c.actorId)
      actor.clearInitiative()
    }
    super._onDelete()
  }

}
