/* -------------------------------------------- */
import { YggdrasillUtility } from "./yggdrasill-utility.js";
import { YggdrasillRoll } from "./yggdrasill-roll-dialog.js";

/* -------------------------------------------- */
const statusEffects = [
  { yggdrasill: true, id: 'epuise', label: 'Epuisé', icon: 'icons/svg/stoned.svg' },
  { yggdrasill: true, id: 'blesse', label: 'Blessé', icon: 'icons/svg/blood.svg' },
  { yggdrasill: true, id: 'meurtri', label: 'Meurtri', icon: 'icons/svg/falling.svg' }
]
const armeCategorieToCompetence = { "lutte": "Lutte", "improvisee": "Armes Improvisées", "courte":"Armes courtes", "longue": "Armes longues", "deuxmains": "Armes à deux mains", 
        "hast": "Armes d'Hast", "tir": "Armes de tir", "jet": "Lancer" }
const attackMode = { 
    "classique": { 
      "categName": "corps",
      "caracName": "agilite",
      "malus": 0,
      "protection": 0,
      "bonusdegats": 0,
      "label": "Attaque Classique",
      "description": "Attaque classique" 
    },
    "force": { 
      "categName": "corps",
      "caracName": "puissance",
      "malus": 0,
      "protection": 0,
      "bonusdegats": "puissance;1",
      "label": "Attaque en Force",
      "description": "Attaque en Force : Malus: 0, +PUI en dégats" 
    },
    "devastatrice": { 
      "categName": "corps",
      "caracName": "puissance",
      "malus": "puissance;1",
      "bonusdegats": "puissance;3",
      "protection": 0,
      "label": "Attaque Dévastatrice",
      "description": "Attaque Dévastratrice : Malus -PUI, +PUI*3 en dégats" 
    },
    "precise": { 
      "categName": "esprit",
      "caracName": "perception",
      "malus": "0",
      "bonusdegats": 0,
      "protection": "perception;1",
      "label": "Attaque Précise",
      "description": "Attaque précise : Malus : 0, protection réduite de -PER" 
    },
    "visee": { 
      "categName": "esprit",
      "caracName": "perception",
      "malus": "perception;1",
      "bonusdegats": 0,
      "protection": "perception;3",
      "label": "Attaque Visée",
      "description": "Attaque visée : Malus : -PER, protection réduite de -PER" 
    }
  }
  const tirMode = { 
    "pose": { 
      "categName": "corps",
      "caracName": "agilite",
      "malus": 0,
      "protection": 0,
      "bonusdegats": 0,
      "label": "Tir posé",
      "description": "Tir posé" 
    },
    "arrettir": { 
      "categName": "ame",
      "caracName": "instinct",
      "malus": 0,
      "protection": 0,
      "bonusdegats": "instinct;1",
      "label": "Tir d'Arrêt (Tir)",
      "description": "Tir d'Arrêt (Tir) : Malus: 0, +INS en dégats" 
    },
    "arretjet": { 
      "categName": "corps",
      "caracName": "puissance",
      "malus": 0,
      "protection": 0,
      "bonusdegats": "puissance;1",
      "label": "Tir d'Arrêt (Jet)",
      "description": "Tir d'Arrêt (Jet) : Malus: 0, +PUI en dégats" 
    },
    "impacttir": { 
      "categName": "ame",
      "caracName": "instinct",
      "malus": "instinct;1",
      "protection": 0,
      "bonusdegats": "instinct;3",
      "label": "Tir d'Impact (Tir)",
      "description": "Tir d'Impact (Tir) : Malus: -INS, +INS*3 en dégats" 
    },
    "impactjet": { 
      "categName": "corps",
      "caracName": "puissance",
      "malus": "puissance;1",
      "protection": 0,
      "bonusdegats": "puissance;3",
      "label": "Attaque d'Impact (Jet)",
      "description": "Attaque d'Impact (Jet) : Malus: -PUI, +PUI*3 en dégats" 
    },
    "precision": { 
      "categName": "esprit",
      "caracName": "perception",
      "malus": "0",
      "bonusdegats": 0,
      "protection": "perception;1",
      "label": "Tir de Précision",
      "description": "Tir de Précision : Malus : 0, protection réduite de -PER" 
    },
    "vise": { 
      "categName": "esprit",
      "caracName": "perception",
      "malus": "perception;1",
      "bonusdegats": 0,
      "protection": "perception;3",
      "label": "Tir Visée",
      "description": "Tir visée : Malus : -PER, protection réduite de -PER" 
    }
  }

/* -------------------------------------------- */
/* -------------------------------------------- */
/**
 * Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
 * @extends {Actor}
 */
export class YggdrasillActor extends Actor {

  /* -------------------------------------------- */
  /**
   * Override the create() function to provide additional SoS functionality.
   *
   * This overrided create() function adds initial items 
   * Namely: Basic skills, money, 
   *
   * @param {Object} data        Barebones actor data which this function adds onto.
   * @param {Object} options     (Unused) Additional options which customize the creation workflow.
   *
   */

  static async create(data, options) {

    // Case of compendium global import
    if (data instanceof Array) {
      return super.create(data, options);
    }
    // If the created actor has items (only applicable to duplicated actors) bypass the new actor creation logic
    if (data.items) {
      let actor = super.create(data, options);
      return actor;
    }

    const competencesGen = await YggdrasillUtility.loadCompendium("fvtt-yggdrasill.competences-generales");
    const competencesMar = await YggdrasillUtility.loadCompendium("fvtt-yggdrasill.competences-martiales");
    const competencesMag = await YggdrasillUtility.loadCompendium("fvtt-yggdrasill.competences-magiques");
    const competences = competencesGen.concat(competencesMar).concat(competencesMag);
    data.items = competences.map(i => i.toObject());

    return super.create(data, options);
  }
    
  /* -------------------------------------------- */
  prepareBaseData() {
    if ( this.type == "personnage") {
      this.computeCaracSecondaire();
    }
  }

  /* -------------------------------------------- */
  async prepareData() {
    if ( this.type == "personnage") {
      this.computeCaracSecondaire();
      if (this.data.data.furor.value == 0) 
        await this.setEpuise();
      else 
        await this.cleanEpuise();
      if ( this.data.data.caracsecondaire.pv.value < (this.data.data.caracsecondaire.pv.max/4) )
        await this.setMeurtri();
      else 
        await this.cleanMeurtri();
      if ( this.data.data.caracsecondaire.pv.value < (this.data.data.caracsecondaire.pv.max/2) )
        await this.setBlesse();
      else 
        await this.cleanBlesse();
    }
    super.prepareData();
  }

  /* -------------------------------------------- */
  _preUpdate(changed, options, user) {
    if ( changed.data?.caracsecondaire?.pv?.value ) {
      if ( changed.data.caracsecondaire.pv.value < 0 ) 
        changed.data.caracsecondaire.pv.value = 0;
      if ( changed.data.caracsecondaire.pv.value > this.data.data.caracsecondaire.pv.max ) 
        changed.data.caracsecondaire.pv.value = this.data.data.caracsecondaire.pv.max;    
    }
    if ( changed.data?.furor?.value ) {
      if ( changed.data.furor.value < 0 ) 
        changed.data.furor.value = 0;
      if ( changed.data.furor.value > this.data.data.furor.max ) 
        changed.data.furor.value = this.data.data.furor.max;
    }
    super._preUpdate(changed, options, user);
  }
  /* -------------------------------------------- */
  getCompetences() {
    let comp = this.data.items.filter( item => item.type == 'competence');
    return comp;
  }
  /* -------------------------------------------- */
  compareName( a, b) {
    if ( a.name < b.name ) {
      return -1;
    }
    if ( a.name > b.name ) {
      return 1;
    }
    return 0;
  }
  /* -------------------------------------------- */
  getInitiativeScore() {
    return this.data.data.caracsecondaire.reaction.max;
  }
  /* -------------------------------------------- */
  getCompetencesGenerales() {
    let comp = this.data.items.filter( item => item.type == 'competence' && item.data.data.categorie == 'generale');
    return comp.sort( this.compareName );
  }
  /* -------------------------------------------- */
  getCompetencesMartiales() {
    let comp =  this.data.items.filter( item => item.type == 'competence' && item.data.data.categorie == 'martiale');
    return comp.sort( this.compareName );
  }
  /* -------------------------------------------- */
  getCompetencesMagiques() {
    let comp =  this.data.items.filter( item => item.type == 'competence' && item.data.data.categorie == 'magique');
    return comp.sort( this.compareName );
  }

  /* -------------------------------------------- */
  getDons( ) {
    let dons = this.data.items.filter( item => item.type == 'don');
    return dons.sort( this.compareName );
  }
  /* -------------------------------------------- */
  getEffetsMagiques( ) {
    let effets = this.data.items.filter( item => item.type == 'effetmagique');
    return effets.sort( this.compareName );
  }
  /* -------------------------------------------- */
  getEffetsDeRunes( ) {
    let effets = this.data.items.filter( item => item.type == 'effetderune');
    return effets.sort( this.compareName );
  }
  
  /* -------------------------------------------- */
  getMonnaies( ) {
    let monnaies = this.data.items.filter( item => item.type == 'monnaie');
    return monnaies.sort( this.compareName );
  }
  /* -------------------------------------------- */
  getFaiblesses( ) {
    let faib = this.data.items.filter( item => item.type == 'faiblesse');
    return faib.sort( this.compareName );
  }
  /* -------------------------------------------- */
  getBlessures( ) {
    return this.data.items.filter( item => item.type == 'blessure');
  }
  /* -------------------------------------------- */
  getToutEquipements() {
    return this.data.items.filter( item => item.type == 'equipement' || item.type == 'armure' || item.type == 'armecc' || item.type == 'armedist');
  }
  /* -------------------------------------------- */
  getArmes() {
    return this.data.items.filter( item => (item.type == 'armecc' || item.type == 'armedist') && item.data.data.equipe );
  }
  /* -------------------------------------------- */
  getArmures() {
    return this.data.items.filter( item => item.type == 'armure' && item.data.data.equipe );
  }
  getProuessesMartiales() {
    let prouesse = this.data.items.filter( item => item.type == 'prouesse' );
    return prouesse.sort( this.compareName );
  }
  getSortsSejdr() {
    let sort =  this.data.items.filter( item => item.type == 'sortsejdr' );
    return sort.sort( this.compareName );
  }
  getSortsGaldr() {
    let sort =  this.data.items.filter( item => item.type == 'sortgaldr' );
    return sort.sort( this.compareName );
  }
  getRunes() {
    let sort =  this.data.items.filter( item => item.type == 'rune' );
    return sort.sort( this.compareName );
  }

  /* -------------------------------------------- */
  async setEpuise( ) {
    await this.update({ 'data.status.epuise': true});
    this.data.data.status.epuise = true;
    /*let effect = this.getEffectByLabel('Epuisé');
    if ( !effect ) {
      let effect = statusEffects.find( ef => ef.id == 'epuise');
      await this.createEmbeddedDocuments("ActiveEffect", [ effect ] );
    }*/
  }
  /* -------------------------------------------- */
  async cleanEpuise() {
    await this.update({ 'data.status.epuise': false});
    this.data.data.status.epuise = false;
    /*let effect = this.getEffectByLabel('Epuisé');
    if ( effect ) {
      await this.deleteEmbeddedDocuments("ActiveEffect", [ effect.id ]);     
    }*/
  }
  /* -------------------------------------------- */
  async toggleEpuise( ) {
    if ( this.data.data.status.epuise ) {
      await this.cleanEpuise();     
    } else {
      await this.setEpuise();
    }
  }
  /* -------------------------------------------- */
  isEpuise() {
    return this.data.data.status.epuise;
  }

  /* -------------------------------------------- */
  async setBlesse( ) {
    await this.update({ 'data.status.blesse': true} );
    this.data.data.status.blesse = true;
    console.log("BLESSSE !!!!");
    /*let effect = this.getEffectByLabel('Blessé');
    if ( !effect ) {
      let effect = statusEffects.find( ef => ef.id == 'blesse');
      await this.createEmbeddedDocuments("ActiveEffect", [ effect ] );
    }*/
  }
  /* -------------------------------------------- */
  async cleanBlesse() {
    await this.update({ 'data.status.blesse': false} );
    this.data.data.status.blesse = false;
    /*let effect = this.getEffectByLabel('Blessé');
    if ( effect ) {
      await this.deleteEmbeddedDocuments("ActiveEffect", [ effect.id ]);     
    }*/
  }

  /* -------------------------------------------- */
  isBlesse() {
    return this.data.data.status.blesse;
    //return this.getEffectByLabel('Blessé');
  }
  /* -------------------------------------------- */
  async setMeurtri( ) {
    await this.setBlesse();
    await this.update({ 'data.status.meurtri': true});
    this.data.data.status.meurtri = true;
  }
  /* -------------------------------------------- */
  async cleanMeurtri() {
    await this.update({ 'data.status.meurtri': false});
    this.data.data.status.meurtri = false;
  }
  /* -------------------------------------------- */
  isMeurtri() {
    return this.data.data.status.meurtri;
  }

  /* -------------------------------------------- */
  async decrementFuror( nbFuror) {
    await this.update( { 'data.furor.value': this.data.data.furor.value - nbFuror } );
  }

  /* -------------------------------------------- */
  getCurrentFuror() {
    return this.data.data.furor.value;
  }

  /* -------------------------------------------- */
  getActiveEffects(matching = it => true) {
    let array = Array.from(this.getEmbeddedCollection("ActiveEffect").values());
    return Array.from(this.getEmbeddedCollection("ActiveEffect").values()).filter(it => matching(it));
  }
  /* -------------------------------------------- */
  getEffectByLabel(label) {
    return this.getActiveEffects().find(it => it.data.label == label);
  }
  /* -------------------------------------------- */
  getEffectById(id) {
    return this.getActiveEffects().find(it => it.id == id);
  }

  /* -------------------------------------------- */
  getCarac( caracName ) {
    for( let key in this.data.data.carac) {
      let categ = this.data.data.carac[key];
      for( let carac in categ.carac) {
        if (carac.toLowerCase() == caracName.toLowerCase() ) {
          return deepClone(categ.carac[carac]);
        }
      }
    }
  }

  /* -------------------------------------------- */
  computeCaracSecondaire( ) {
    if ( this.type == "personnage") { 
      let basecorps = this.data.data.carac.corps.carac;
      let sumcorps = basecorps.puissance.value + basecorps.agilite.value + basecorps.vigueur.value
      let baseesprit = this.data.data.carac.esprit.carac;
      let sumesprit = baseesprit.intellect.value + baseesprit.perception.value + baseesprit.tenacite.value
      let baseame = this.data.data.carac.ame.carac;
      let sumame = baseame.charisme.value + baseame.communication.value + baseame.instinct.value
      
      let newPV = (sumcorps*3) + (sumesprit *2) + sumame;
      if ( newPV != this.data.data.caracsecondaire.pv.max) {      
        this.data.data.caracsecondaire.pv.max = newPV;
        this.update( { 'data.caracsecondaire.pv.max': newPV });
      }

      this.data.data.caracsecondaire.reaction.value = baseesprit.intellect.value + baseesprit.perception.value + baseame.instinct.value;
      this.data.data.caracsecondaire.reaction.max = baseesprit.intellect.value + baseesprit.perception.value + baseame.instinct.value;

      this.data.data.caracsecondaire.defensephy.value = basecorps.agilite.value + basecorps.vigueur.value + baseame.instinct.value;
      this.data.data.caracsecondaire.defensephy.max = basecorps.agilite.value + basecorps.vigueur.value + baseame.instinct.value;

      this.data.data.caracsecondaire.defensemen.value = baseesprit.tenacite.value + baseame.instinct.value + baseesprit.intellect.value;
      this.data.data.caracsecondaire.defensemen.max = baseesprit.tenacite.value + baseame.instinct.value + baseesprit.intellect.value;

      this.data.data.caracsecondaire.deplacement.value = basecorps.agilite.value + basecorps.vigueur.value;
      this.data.data.caracsecondaire.deplacement.max = basecorps.agilite.value + basecorps.vigueur.value;

      this.data.data.caracsecondaire.capaenc.value = (basecorps.puissance.value * 2) + basecorps.vigueur.value;
      this.data.data.caracsecondaire.capaenc.max = (basecorps.puissance.value * 2) + basecorps.vigueur.value;
    }
  }

  /* -------------------------------------------- */
  async equiperObject( equipementId ) {    
    let item = this.data.items.find( item => item.id == equipementId );
    if (item && item.data.data) {
      let update = { _id: item.id, "data.equipe": !item.data.data.equipe };
      await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
    }
  }
  /* -------------------------------------------- */
  async updateCompetence( compId, niveau) {
    let comp = this.data.items.find( item => item.type == 'competence' && item.id == compId);
    console.log("Comp updated!!!!", compId, niveau);
    if (comp) {
      const update = { _id: comp.id, 'data.niveau': niveau };
      await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
    } else {
      ui.notifications.warn("Compétence inconnue", compId)
    }
  }

  /* -------------------------------------------- */
  buildListeActionsCombat( ) {
    let armes = [];
  }
  
  /* -------------------------------------------- */
  async rollAttribute( attrkey, subAttrKey = 'defaut') {
    let attr = duplicate(this.data.data.attributs[attrkey]);
    let subAttr = duplicate(this.data.data.attributs[attrkey].values[subAttrKey] );
    console.log("ATTR : ", attr, subAttr);
    if ( attr ) {
      subAttr.label = subAttr.label || "";
      let title = `Attribut : ${attr.label} ${subAttr.label} :  ${subAttr.value}`;
      let rollData = {
        mode: "attribut",
        alias: this.name, 
        actorImg: this.img,
        actorId: this.id,
        attr: attr,
        valuePhysique: this.data.data.attributs["physique"].values["defaut"].value,
        subAttr: subAttr,
        rollMode: game.settings.get("core", "rollMode"),
        title: title,
        isBlesse: this.data.data.etat.etat == "blesse",
        optionsBonusMalus: YggdrasillUtility.buildListOptions(-6, +6),
        bonusMalus: 0,
        optionsSR: YggdrasillUtility.buildSROptions( ),
        sr: 0
      }
      let rollDialog = await YggdrasillRoll.create( this, rollData);
      console.log(rollDialog);
      rollDialog.render( true );
    } else {
      ui.notifications.warn("Attribut non trouvée");
    }
  }

  /* -------------------------------------------- */
  async rollCarac( categName, caracName) {
    let carac = duplicate(this.data.data.carac[categName].carac[caracName]);
    console.log("CARAC : ", carac, this.data.data.carac);
    if ( carac) {
      let rollData = {
        mode: "carac",
        alias: this.name, 
        actorImg: this.img,
        actorId: this.id,
        img: `systems/fvtt-yggdrasill/images/icons/icon_carac_${categName}.png`,
        rollMode: game.settings.get("core", "rollMode"),
        title: `Caractéristique ${carac.label} : ${carac.value}`,
        selectedCarac: carac, 
        isEpuise: this.isEpuise(),
        isBlesse: this.isBlesse(),
        isMeurtri: this.isMeurtri(),
        optionsBonusMalus: YggdrasillUtility.buildListOptions(-6, +6),
        bonusMalus: 0,
        optionsFuror: YggdrasillUtility.buildListOptions(0, this.getCurrentFuror() ),
        furorUsage: 0,
        optionsSR: YggdrasillUtility.buildSROptions( ),
        sr: 0
      }
      let rollDialog = await YggdrasillRoll.create( this, rollData);
      console.log(rollDialog);
      rollDialog.render( true );
    } else {
      ui.notifications.warn("Caractéristique non trouvée");
    }

  }

  /* -------------------------------------------- */
  async rollCompetence( competenceId ) {
    let competence = this.data.items.find( item => item.type == 'competence' && item.id == competenceId);
    if ( competence) {
      let rollData = {
        mode: "competence",
        alias: this.name, 
        actorImg: this.img,
        actorId: this.id,
        img: competence.img,
        rollMode: game.settings.get("core", "rollMode"),
        title: `Compétence ${competence.name} : ${competence.data.data.niveau}`,
        competence: duplicate(competence),
        isEpuise: this.isEpuise(),
        isBlesse: this.isBlesse(),
        isMeurtri: this.isMeurtri(),
        optionsBonusMalus: YggdrasillUtility.buildListOptions(-6, +6),
        bonusMalus: 0,
        optionsFuror: YggdrasillUtility.buildListOptions(0, this.getCurrentFuror() ),
        furorUsage: 0,
        optionsSR: YggdrasillUtility.buildSROptions( ),
        sr: 0
      }
      let rollDialog = await YggdrasillRoll.create( this, rollData);
      console.log(rollDialog);
      rollDialog.render( true );
    } else {
      ui.notifications.warn("Compétence non trouvée");
    }
  }

  /* -------------------------------------------- */
  getAttaqueData( mode ) {
    let attackData = duplicate(attackMode[mode]);
    if ( attackData){
      attackData.mode = mode;
      attackData.carac = duplicate(this.data.data.carac[attackData.categName].carac[attackData.caracName]);
      if ( attackData.malus != 0) {
        let malusTab = attackData.malus.split(';');
        attackData.malus = this.data.data.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
      if ( attackData.protection != 0) {
        let malusTab = attackData.protection.split(';');
        attackData.protection = this.data.data.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
      if ( attackData.bonusdegats != 0) {
        let malusTab = attackData.bonusdegats.split(';');
        attackData.bonusdegats = this.data.data.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
    }
    return attackData;
  }

  /* -------------------------------------------- */
  getTirData( mode) {
    let attackData = duplicate( tirMode[mode] );
    if ( attackData){
      attackData.mode = mode;
      attackData.carac = duplicate(this.data.data.carac[attackData.categName].carac[attackData.caracName]);
      if ( attackData.malus != 0) {
        let malusTab = attackData.malus.split(';');
        attackData.malus = this.data.data.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
      if ( attackData.protection != 0) {
        let malusTab = attackData.protection.split(';');
        attackData.protection = this.data.data.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
      if ( attackData.bonusdegats != 0) {
        let malusTab = attackData.bonusdegats.split(';');
        attackData.bonusdegats = this.data.data.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
    }
    return attackData;
  }

  /* -------------------------------------------- */
  async rollSort( sortId, magie) {
    let sort = this.data.items.find( item => item.id == sortId);
    let competence = this.data.items.find( item => item.type == 'competence' && item.name.toLowerCase().includes(magie));
    console.log("SORT :", sortId, sort, competence );
  
    let carac;
    if ( magie == "sejdr")  {
      carac =  duplicate(this.data.data.carac.ame.carac.instinct);
    } else if ( magie == "rune") {
      carac =  duplicate(this.data.data.carac.ame.carac.communication);
    } else {
      carac =  duplicate(this.data.data.carac.ame.carac.charisme);
    }

    if ( sort && competence) {
      
      let rollData = {
        mode: magie,
        alias: this.name, 
        actorImg: this.img,
        actorId: this.id,
        img: sort.img,
        rollMode: game.settings.get("core", "rollMode"),
        title: magie + " - " + sort.name,
        selectedCarac: carac, 
        agiliteCarac: duplicate(this.data.data.carac.corps.carac.agilite),
        instinctCarac: duplicate(this.data.data.carac.ame.carac.instinct),
        sort: duplicate(sort),
        competence: duplicate(competence),
        dureeGaldr: "1d5a",
        nbCibles: "1",
        zoneGaldr: "INS10cm3",
        bonusdefense: 0,
        isEpuise: this.isEpuise(),
        isBlesse: this.isBlesse(),
        isMeurtri: this.isMeurtri(),
        optionsBonusMalus: YggdrasillUtility.buildListOptions(-6, +6),
        optionsBD: YggdrasillUtility.buildListOptions(0, +6),
        bonusMalus: 0,
        optionsFuror: YggdrasillUtility.buildListOptions(0, this.getCurrentFuror() ),
        furorUsage: 0,
        optionsSR: YggdrasillUtility.buildSROptions( ),
        sr: 14,
        puissanceRune: 1,
        optionsPuissanceRune: YggdrasillUtility.buildListOptions(1, 15),
        supportRune: "peau",
      }
      let rollDialog = await YggdrasillRoll.create( this, rollData);
      console.log(rollDialog);
      rollDialog.render( true );
    } else {
      ui.notifications.warn("Sortilège ou Compétence non trouvée !", sort, compName);
    }
  }

  /* -------------------------------------------- */
  async rollArme( armeId ) {
    let arme = this.data.items.find( item => item.id == armeId);
    let compName = armeCategorieToCompetence[arme.data.data.categorie];
    let competence = this.data.items.find( item => item.type == 'competence' && item.name == compName);
    console.log("ARME :", armeId, arme, competence );
    
    if ( arme && competence) {
      
      let attackDef
      if (arme.type == 'armecc') {
        attackDef = this.getAttaqueData("classique");
      } else { 
        attackDef = this.getTirData("pose");
      }

      let rollData = {
        mode: arme.type,
        attackDef: attackDef,
        alias: this.name, 
        actorImg: this.img,
        actorId: this.id,
        img: competence.img,
        rollMode: game.settings.get("core", "rollMode"),
        title: "Attaque !",
        selectedCarac: duplicate(this.data.data.carac.corps.carac.agilite),
        arme: duplicate(arme),
        competence: duplicate(competence),
        bonusdefense: 0,
        isEpuise: this.isEpuise(),
        isBlesse: this.isBlesse(),
        isMeurtri: this.isMeurtri(),
        optionsBonusMalus: YggdrasillUtility.buildListOptions(-6, +6),
        optionsBD: YggdrasillUtility.buildListOptions(0, +6),
        bonusMalus: 0,
        optionsFuror: YggdrasillUtility.buildListOptions(0, this.getCurrentFuror() ),
        furorUsage: 0,
        optionsSR: YggdrasillUtility.buildSROptions( ),
        sr: 14
      }
      let rollDialog = await YggdrasillRoll.create( this, rollData);
      console.log(rollDialog);
      rollDialog.render( true );
    } else {
      ui.notifications.warn("Arme ou Compétence Martiale non trouvée !", arme, compName);
    }
  }
  
  /* -------------------------------------------- */
  getEncTotal( ) {
    let encTotal = 0;
    for( let item of this.data.items) {
      if (item.type == "equipement" || item.type == "armecc" 
      || item.type == "armedist" || item.type == "armure" || item.type == "monnaie") {
        encTotal += item.data.data.enc;
      }
    }
    return encTotal;
  } 

  /* -------------------------------------------- */
  getProtectionTotal( ) {
    let protectionTotal = 0;
    for( let item of this.data.items) {
      if (item.type == "armure" && item.data.data.equipe) {
        protectionTotal += Number(item.data.data.protection);
      }
    }
    return protectionTotal;
  } 

  /* -------------------------------------------- */
  async incrementeQuantite( objetId ) {
    let objetQ = this.data.items.find( item => item.id == objetId );
    if (objetQ) {
      let newQ = objetQ.data.data.quantite + 1;
      const updated = await this.updateEmbeddedDocuments('Item', [{ _id: objetQ.id, 'data.quantite': newQ }]); // pdates one EmbeddedEntity
    }
  }
  
  /* -------------------------------------------- */
  async decrementeQuantite( objetId ) {
    let objetQ = this.data.items.find( item => item.id == objetId );
    if (objetQ) {
      let newQ = objetQ.data.data.quantite - 1;
      newQ = (newQ <= 0) ? 0 : newQ;
      const updated = await this.updateEmbeddedDocuments('Item', [{ _id: objetQ.id, 'data.quantite': newQ }]); // pdates one EmbeddedEntity
    }
  }
    
}