/**
 * Donjon & Cie - Systeme FoundryVTT
 *
 * Donjon & Cie est un jeu de role edite par John Doe.
 * Ce systeme FoundryVTT est une implementation independante et n'est pas
 * affilie a John Doe.
 *
 * @author    LeRatierBretonnien
 * @copyright 2025–2026 LeRatierBretonnien
 * @license   CC BY-NC-SA 4.0 – https://creativecommons.org/licenses/by-nc-sa/4.0/
 */

import { DonjonEtCieRollDialog } from "./applications/donjon-et-cie-roll-dialog.mjs";
import { DonjonEtCieUtility } from "./donjon-et-cie-utility.mjs";

export class DonjonEtCieItem extends Item {
  async _preCreate(data, options, user) {
    await super._preCreate(data, options, user);

    const currentImg = data.img ?? this.img;
    if (currentImg && !currentImg.startsWith("icons/svg/")) return;

    this.updateSource({ img: DonjonEtCieUtility.getDefaultItemIcon(this.type) });
  }

  get usageDie() {
    return Number(this.system.delta ?? 0);
  }

  get usageDieMax() {
    return Number(this.system.deltaMax ?? this.system.delta ?? 0);
  }

  get ammunitionUsageDie() {
    return Number(this.system.munitionsDelta ?? 0);
  }

  get damageUsageDie() {
    return Number(this.system.degatsDelta ?? 0);
  }

  async roll() {
    if (this.type === "arme") return DonjonEtCieRollDialog.createWeapon(this.actor, this);
    if (this.type === "sortilege") return DonjonEtCieRollDialog.createSpell(this.actor, this);
    if (this.usageDie) return DonjonEtCieRollDialog.createUsage(this);
    if (this.type === "entrainement" && this.usageDieMax > 0) {
      ui.notifications.warn(game.i18n.localize("DNC.Warn.TrainingExhausted"));
      return null;
    }
    return this.postToChat();
  }

  async rollDamage() {
    if (this.system.degatsEstUsageDe) {
      if (!Number(this.system.degatsDelta ?? 0)) {
        ui.notifications.warn(game.i18n.localize("DNC.Warn.DamageExhausted"));
        return null;
      }
    } else if (!this.system.degats) {
      return null;
    }
    return DonjonEtCieRollDialog.createDamage(this.actor, this);
  }

  async rollAmmoUsage() {
    if (this.type !== "arme") return null;
    return game.system.donjonEtCie.rolls.rollWeaponAmmoUsage(this);
  }

  async rollDamageUsage() {
    if (this.type !== "arme") return null;
    return game.system.donjonEtCie.rolls.rollWeaponDamageUsage(this);
  }

  async postToChat() {
    const content = await foundry.applications.handlebars.renderTemplate(
      "systems/fvtt-donjon-et-cie/templates/chat/item-card.hbs",
      {
        item: this,
        usageLabel: DonjonEtCieUtility.formatUsageDie(this.usageDie)
      }
    );

    return ChatMessage.create({
      speaker: ChatMessage.getSpeaker({ actor: this.actor }),
      user: game.user.id,
      content
    });
  }

  async resetUsageDie() {
    if (this.type !== "entrainement") return this;
    const deltaMax = this.usageDieMax;
    if (!deltaMax) return this;
    return this.update({ "system.delta": deltaMax });
  }
}
