/*
Init order = 
  10 - Legendary
  9 - Heroic
  8 - Success
  7 - Rivals/adversary
  6 - Coriaces/tough
  5 - Failure
  4 - Pietaille
  3 - Echec critique
*/

import { BoLUtility } from "../system/bol-utility.js";


export class BoLCombatManager extends Combat {

  /************************************************************************************/
  async rollInitiative(ids, formula = undefined, messageOptions = {}) {
    console.log(`${game.system.title} | Combat.rollInitiative()`, ids, formula, messageOptions);
    // Structure input data
    ids = typeof ids === "string" ? [ids] : ids;
    // Get initiative malus from tough/adversary
    let malusInit = 0 
    for (let combatant of this.combatants) {
      malusInit = Math.max(malusInit, combatant.actor.getInitiativeMalus())
    }
    // calculate initiative
    for (let cId = 0; cId < ids.length; cId++) {     
      const combatant = this.combatants.get(ids[cId])
      let fvttInit = combatant.actor.getInitiativeRank(false, true, { combatId: this.id, combatantId: combatant.id, malusInit })
      fvttInit += (cId / 100)
      await this.updateEmbeddedDocuments("Combatant", [{ _id: ids[cId], initiative: fvttInit }]);
    }
  }

  /************************************************************************************/
  nextRound() {
    if (game.user.isGM) {
      let combatants = this.combatants.contents
      let autoRemoveDead = game.settings.get("bol", "auto-remove-dead") // Optionnal auto-removal of dead char.
      for (let c of combatants) {
        //let actor = game.actors.get(c.actorId)
        c.actor.clearRoundModifiers()
        let toRemove = []
        if (autoRemoveDead && c.actor.type == "encounter" && (c.actor.system.chartype == "tough" || c.actor.system.chartype == "creature" || c.actor.system.chartype == "base") && c.actor.system.resources.hp.value <= 0) {
          toRemove.push(c.id || c._id)
        }
        //console.log("REM", autoRemoveDead, toRemove, c.actor)
        if (toRemove.length > 0) {
          this.deleteEmbeddedDocuments('Combatant', toRemove)
        }
      }
    }
    super.nextRound()
  }

  /************************************************************************************/
  startCombat() {
    if (game.user.isGM) {
      let combatants = this.combatants.contents
      for (let c of combatants) {
        let actor = game.actors.get(c.actorId)
        actor.storeVitaliteCombat()
      }
    }
    return super.startCombat()
  }

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

}

