import { ChatUtility } from "../chat-utility.js";
import { RdDItem } from "../item.js";
import { Misc } from "../misc.js";
import { RdDTimestamp } from "../time/rdd-timestamp.js";

export class RdDItemMaladie extends RdDItem {

  static get defaultIcon() {
    return "systems/foundryvtt-reve-de-dragon/icons/maladies_venins/maladie.webp";
  }

  async calculerFinPeriodeTemporel(debut) {
    return await debut.addPeriode(this.system.periode.nombre, this.system.periode.unite);
  }

  async onFinPeriode(oldTimestamp, newTimestamp) {
    await RdDItemMaladie.notifierMaladiePoison(this, oldTimestamp, newTimestamp)
  }

  static async notifierMaladiePoison(mal, oldTimestamp, newTimestamp) {
    if (mal.actor) {
      const souffrance = mal.system.identifie
        ? `de ${mal.name}`
        : `d'un mal inconnu`
      ChatMessage.create({
        whisper: ChatUtility.getOwners(mal.actor),
        content: `${mal.actor.name} souffre ${souffrance} (${Misc.typeName('Item', mal.type)}): vérifiez que les effets ne se sont pas aggravés !`
      })
      mal.postItemToChat('gmroll')
      await RdDItemMaladie.prolongerPeriode(mal, oldTimestamp, newTimestamp)
    }
  }

  static async prolongerPeriode(mal, oldTimestamp, newTimestamp) {
    if (mal.actor) {
      // TODO: déterminer le nombre de périodes écoulées
      console.log(`${mal.actor.name}: le mal ${mal.name} a atteint la fin de sa période et été prolongé`);
      const current = newTimestamp;
      const finPeriode = new RdDTimestamp(mal.system.temporel.fin)
      const periodeSuivante = (finPeriode.compare(current) > 0 ? finPeriode : current);
      const timestampFin = await mal.calculerFinPeriodeTemporel(periodeSuivante);

      await mal.actor.updateEmbeddedDocuments('Item', [{
        _id: mal.id,
        'system.temporel.fin': foundry.utils.duplicate(timestampFin),
      }])
    }
  }


}