import { DarkStarsUtility } from "./dark-stars-utility.js";

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

  /* -------------------------------------------- */
  processOtherTurns(c, initScore) {
    let toCreate = []
    let token = canvas.tokens.get(c.tokenId)
    let hasLastWord = token.actor.hasLastWord()
    while ( (initScore > 5) || (hasLastWord && initScore >= 5)) {
      initScore -= 5;
      toCreate.push({tokenId: c.tokenId, sceneId: c.sceneId, actorId: c.actorId, hidden: c.hidden, initiative: initScore, flags: { world: { isDuplicated: true} } } );
    }
    this.createEmbeddedDocuments("Combatant", toCreate);
  }

  /* -------------------------------------------- */
  async rollInitiative(ids, formula = undefined, messageOptions = {}) {
    ids = typeof ids === "string" ? [ids] : ids;
    for (let cId of ids) {
      const c = this.combatants.get(cId);
      let id = c._id || c.id;
      let initScore = c.actor ? c.actor.getInitiativeScore(this.id, id) : -1;
      await this.updateEmbeddedDocuments("Combatant", [{ _id: id, initiative: initScore }]);
      setTimeout(() => this.processOtherTurns(c, initScore), 400)
    }
    return this;
  }

  /* -------------------------------------------- */
  nextRound() {
    super.nextRound()
    let toDelete = []
    for (let c of this.combatants) {
      if (c.flags?.world?.isDuplicated) {
        toDelete.push(c._id)
      }
    }
    this.deleteEmbeddedDocuments("Combatant", toDelete);
  }

  /* -------------------------------------------- */
  _onUpdate(changed, options, userId) {
  }

}
