import MyriadSystemItemBase from "./base-item.mjs";

export default class MyriadSystemItem extends MyriadSystemItemBase {

  static defineSchema() {
    const fields = foundry.data.fields;
    const requiredInteger = { required: true, nullable: false, integer: true };
    const schema = super.defineSchema();

    schema.quantity = new fields.NumberField({ ...requiredInteger, initial: 1, min: 1 });
    schema.weight = new fields.NumberField({ required: true, nullable: false, initial: 0, min: 0 });
    
    // Nombre de cases occupées dans la grille d'inventaire
    schema.dimensionCases = new fields.NumberField({ ...requiredInteger, initial: 1, min: 1 });
    
    // Format de l'objet dans la grille ("1x1", "1x2", "2x2", etc.)
    schema.shape = new fields.StringField({ initial: "1x1" });
    
    // Type d'encombrement (Léger, Normal, Encombrant, Très encombrant)
    schema.encumbranceType = new fields.StringField({
      initial: "normal",
      choices: ["light", "normal", "heavy", "veryHeavy"]
    });
    
    // Emplacement où l'objet est équipé (null si dans l'inventaire)
    schema.equippedSlot = new fields.StringField({ required: false, nullable: true });

    // Break down roll formula into three independent fields
    schema.roll = new fields.SchemaField({
      diceNum: new fields.NumberField({ ...requiredInteger, initial: 1, min: 1 }),
      diceSize: new fields.StringField({ initial: "d20" }),
      diceBonus: new fields.StringField({ initial: "+@puissance.mod+ceil(@lvl / 2)" })
    });

    schema.formula = new fields.StringField({ blank: true });

    return schema;
  }

  prepareDerivedData() {
    super.prepareDerivedData();
    
    // Build the formula dynamically using string interpolation
    const roll = this.roll;
    this.formula = `${roll.diceNum}${roll.diceSize}${roll.diceBonus}`;
    
    // Add default properties as tags if they don't exist
    if (!this.tags) this.tags = [];
    
    // Check if item has specific properties based on tags
    this._isUsable = this.tags.includes("Utilisable");
    this._isEquippable = this.tags.includes("Équipable");
    this._isMagical = this.tags.includes("Magique");
    this._isConsumable = this.tags.includes("Consommable");
    this._isThrowable = this.tags.includes("Jetable");
    
    // Calculate total weight
    this._totalWeight = this.weight * this.quantity;
  }
  
  /**
   * Vérifie si l'objet peut être utilisé.
   * @returns {boolean} - Vrai si l'objet est utilisable.
   */
  canUse() {
    return this._isUsable;
  }
  
  /**
   * Vérifie si l'objet peut être équipé.
   * @returns {boolean} - Vrai si l'objet est équipable.
   */
  canEquip() {
    return this._isEquippable;
  }
}