/* -------------------------------------------- */
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.system.furor.value == 0) 
        await this.setEpuise();
      else 
        await this.cleanEpuise();
      if ( this.system.caracsecondaire.pv.value < (this.system.caracsecondaire.pv.max/4) )
        await this.setMeurtri();
      else 
        await this.cleanMeurtri();
      if ( this.system.caracsecondaire.pv.value < (this.system.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.system.caracsecondaire.pv.max ) 
        changed.data.caracsecondaire.pv.value = this.system.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.system.furor.max ) 
        changed.data.furor.value = this.system.furor.max;
    }
    super._preUpdate(changed, options, user);
  }
  /* -------------------------------------------- */
  getCompetences() {
    let comp = this.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() {
    if ( this.type == 'personnage') {
      return this.system.caracsecondaire.reaction.max;
    } else {
      return this.system.attributs.physique.values.defaut.value;
    }
  }

  /* -------------------------------------------- */
  getCompetencesGenerales() {
    let comp = this.items.filter( item => item.type == 'competence' && item.system.categorie == 'generale');
    return comp.sort( this.compareName );
  }
  /* -------------------------------------------- */
  getCompetencesMartiales() {
    let comp =  this.items.filter( item => item.type == 'competence' && item.system.categorie == 'martiale');
    return comp.sort( this.compareName );
  }
  /* -------------------------------------------- */
  getCompetencesMagiques() {
    let comp =  this.items.filter( item => item.type == 'competence' && item.system.categorie == 'magique');
    return comp.sort( this.compareName );
  }

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

  /* -------------------------------------------- */
  async setEpuise( ) {
    if (!this.system.status.epuise) {
      await this.update({ 'system.status.epuise': true});
      this.system.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() {
    if (this.system.status.epuise) {
      await this.update({ 'system.status.epuise': false});
      this.system.status.epuise = false;
    }
    /*let effect = this.getEffectByLabel('Epuisé');
    if ( effect ) {
      await this.deleteEmbeddedDocuments("ActiveEffect", [ effect.id ]);     
    }*/
  }
  /* -------------------------------------------- */
  async toggleEpuise( ) {
    if ( this.system.status.epuise ) {
      await this.cleanEpuise();     
    } else {
      await this.setEpuise();
    }
  }
  /* -------------------------------------------- */
  isEpuise() {
    return this.system.status.epuise;
  }

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

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

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

  /* -------------------------------------------- */
  getCurrentFuror() {
    return this.system.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.system.carac) {
      let categ = this.system.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.system.carac.corps.carac;
      let sumcorps = basecorps.puissance.value + basecorps.agilite.value + basecorps.vigueur.value
      let baseesprit = this.system.carac.esprit.carac;
      let sumesprit = baseesprit.intellect.value + baseesprit.perception.value + baseesprit.tenacite.value
      let baseame = this.system.carac.ame.carac;
      let sumame = baseame.charisme.value + baseame.communication.value + baseame.instinct.value
      
      let newPV = (sumcorps*3) + (sumesprit *2) + sumame;
      if ( newPV != this.system.caracsecondaire.pv.max) {      
        this.system.caracsecondaire.pv.max = newPV;
        this.update( { 'system.caracsecondaire.pv.max': newPV });
      }

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

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

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

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

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

  /* -------------------------------------------- */
  async equiperObject( equipementId ) {    
    let item = this.items.find( item => item.id == equipementId );
    if (item && item.system) {
      let update = { _id: item.id, "data.equipe": !item.system.equipe };
      await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
    }
  }
  /* -------------------------------------------- */
  async updateCompetence( compId, niveau) {
    let comp = this.items.find( item => item.type == 'competence' && item.id == compId);
    console.log("Comp updated!!!!", compId, niveau);
    if (comp) {
      const update = { _id: comp.id, 'system.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.system.attributs[attrkey]);
    console.log("ATTR : ", attr, attrkey, subAttrKey);
    let subAttr = duplicate(this.system.attributs[attrkey].values[subAttrKey] );
    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.system.attributs["physique"].values["defaut"].value,
        subAttr: subAttr,
        rollMode: game.settings.get("core", "rollMode"),
        title: title,
        isBlesse: this.system.etat.etat == "blesse",
        optionsBonusMalus: YggdrasillUtility.buildListOptions(-15, +15),
        bonusMalus: 0,
        bonusdefense: 0,
        optionsBD: YggdrasillUtility.buildListOptions(0, +15),
        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.system.carac[categName].carac[caracName]);
    console.log("CARAC : ", carac, this.system.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(-15, +15),
        bonusMalus: 0,
        optionsFuror: YggdrasillUtility.buildListOptions(0, this.getCurrentFuror() ),
        furorUsage: 0,
        optionsSR: YggdrasillUtility.buildSROptions( ),
        optionsBD: YggdrasillUtility.buildListOptions(0, +15),
        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.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.system.niveau}`,
        competence: duplicate(competence),
        isEpuise: this.isEpuise(),
        isBlesse: this.isBlesse(),
        isMeurtri: this.isMeurtri(),
        optionsBonusMalus: YggdrasillUtility.buildListOptions(-15, +15),
        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.system.carac[attackData.categName].carac[attackData.caracName]);
      if ( attackData.malus != 0) {
        let malusTab = attackData.malus.split(';');
        attackData.malus = this.system.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
      if ( attackData.protection != 0) {
        let malusTab = attackData.protection.split(';');
        attackData.protection = this.system.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
      if ( attackData.bonusdegats != 0) {
        let malusTab = attackData.bonusdegats.split(';');
        attackData.bonusdegats = this.system.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.system.carac[attackData.categName].carac[attackData.caracName]);
      if ( attackData.malus != 0) {
        let malusTab = attackData.malus.split(';');
        attackData.malus = this.system.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
      if ( attackData.protection != 0) {
        let malusTab = attackData.protection.split(';');
        attackData.protection = this.system.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
      if ( attackData.bonusdegats != 0) {
        let malusTab = attackData.bonusdegats.split(';');
        attackData.bonusdegats = this.system.carac[attackData.categName].carac[malusTab[0]].value * Number(malusTab[1]) 
      }
    }
    return attackData;
  }

  /* -------------------------------------------- */
  async rollSort( sortId, magie) {
    let sort = this.items.find( item => item.id == sortId);
    let competence = this.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.system.carac.ame.carac.instinct);
    } else if ( magie == "rune") {
      carac =  duplicate(this.system.carac.ame.carac.communication);
    } else {
      carac =  duplicate(this.system.carac.ame.carac.charisme);
    }

    if ( sort && competence) {
      
      let rollData = {
        mode: magie,
        isMagie: true,
        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.system.carac.corps.carac.agilite),
        instinctCarac: duplicate(this.system.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(-15, +15),
        optionsBD: YggdrasillUtility.buildListOptions(0, +15),
        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.items.find( item => item.id == armeId);
    let compName = armeCategorieToCompetence[arme.system.categorie];
    let competence = this.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.system.carac.corps.carac.agilite),
        arme: duplicate(arme),
        competence: duplicate(competence),
        bonusdefense: 0,
        isEpuise: this.isEpuise(),
        isBlesse: this.isBlesse(),
        isMeurtri: this.isMeurtri(),
        optionsBonusMalus: YggdrasillUtility.buildListOptions(-15, +15),
        optionsBD: YggdrasillUtility.buildListOptions(0, +15),
        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.items) {
      if (item.type == "equipement" || item.type == "armecc"
      || item.type == "armedist" || item.type == "armure" || item.type == "monnaie" || item.type == "bouclier") {
        encTotal += (item.system.enc * item.system.quantite);
      }
    }
    for( let item of this.items) {
      if (item.type == "bouclier" && item.system.equipe) {
        encTotal -= (item.system.enc * item.system.quantite);
        encTotal += (item.system.enccomb * item.system.quantite);
      }
    }
    return encTotal;
  }

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

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