import { ITEM_TYPES, RdDItem } from "../item.js";
import { Misc } from "../misc.js";
import { ReglesOptionnelles } from "../settings/regles-optionnelles.js";

export class RdDItemArmure extends RdDItem {

  static get ITEM_TYPE() { return ITEM_TYPES.armure }

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

  deteriorerArmure(dmg) {
    if (!ReglesOptionnelles.isUsing('deteriorationArmure') || this.system.protection == '0') {
      return;
    }
    let deterioration = (this.system.deterioration ?? 0) + dmg;
    let protection = this.system.protection;

    if (deterioration >= 10) {
      deterioration -= 10;
      protection = this.calculProtectionDeterioree();
      ChatMessage.create({ content: `Votre armure ${this.name} s'est détériorée, elle protège maintenant de ${protection}` });
    }
    this.update({
      system: {
        deterioration: deterioration,
        protection: protection
      }
    });
  }

  calculProtectionDeterioree() {
    const protectionCourante = this.system.protection;
    let res = /(\d+)?d(\d+)(\-\d+)?/.exec(protectionCourante);
    if (res) {
      let protection = Misc.toInt(res[2]);
      let malus = Misc.toInt(res[3]) - 1;
      if (protection + malus <= 0) {
        return 0;
      } else {
        return `1d${protection}${malus}`;
      }
    }
    else if (/\d+/.exec(protectionCourante)) {
      return `1d${protectionCourante}`;
    }
    else {
      ui.notifications.warn(`La valeur d'armure de votre ${this.name} est incorrecte`);
      return undefined;
    }
  }
}