/* -------------------------------------------- */
import { Misc } from "./misc.js";
import { RdDDice } from "./rdd-dice.js";
import { RdDUtility } from "./rdd-utility.js";
import { RdDCombat } from "./rdd-combat.js";
import { RdDResolutionTable } from "./rdd-resolution-table.js";
import { RdDRoll } from "./rdd-roll.js";
import { RdDRollTables } from "./rdd-rolltables.js";
import { RdDItemCompetenceCreature } from "./item-competencecreature.js";

/* -------------------------------------------- */
/* On part du principe qu'une entité démarre tjs 
une possession via le MJ (ie un joueur ne controle pas une entité)
Donc la compétence Possession ne peut être démarrée que par le MJ.
*/

/* -------------------------------------------- */
export class RdDPossession {

  /* -------------------------------------------- */
  static init() {
  }

  /* -------------------------------------------- */
  static searchPossessionFromEntite( attacker, defender) {
    let poss = attacker.data.items.find( poss => poss.type == 'possession' && poss.data.data.possedeid == defender.data._id);
    if (!poss) {
      poss = defender.data.items.find( poss => poss.type == 'possession' && poss.data.data.possedeid == defender.data._id);
    }
    return poss && duplicate(poss) || undefined;
  }

  /* -------------------------------------------- */
  static updateEtatPossession( possession ) {
    possession.ptsConjuration = 0;
    possession.ptsPossession = 0;
    if ( possession.data.compteur > 0) {
      possession.ptsPossession = possession.data.compteur;
    } 
    if ( possession.data.compteur < 0) {
      possession.ptsConjuration = Math.abs(possession.data.compteur);
    } 
    if (possession.ptsPossession >= 2 ) {
      // Possede
    }
    if (possession.ptsConjuration <= -2 ) {      
      // Libere
    }
    console.log("Poss", possession);
  }

  /* -------------------------------------------- */
  static resultConjuration( rollData) {
    console.log("RollData!!!", rollData);
    if ( !rollData.rolled.isSuccess  ) {
      rollData.possession.data.compteur++;
    }
    this.updateEtatPossession(rollData.possession);
    RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-possession.html');
  }

  /* -------------------------------------------- */
  static async onDefensePossession( actorId, possessionId) {
    let actor = game.actors.get(actorId);
    console.log("onDefensePossession", actor, possessionId);
    let possession = duplicate(actor.items.find( item => item.type =='possession' && item.data.data.possessionid == possessionId));
    let attacker = game.actors.get(possession.data.possesseurid);

    // Update for draconic roll
    let rollData = {
      possession: possession
    }
    rollData.actor = actor;
    rollData.competence = duplicate(actor.getDraconicOrZero());
    rollData.competence.data.defaut_carac = 'reve-actuel';
    rollData.forceCarac = { 'reve-actuel': { label: "Rêve Actuel", value: actor.getReveActuel() } }
    rollData.mode =  "conjuration";
    rollData.possesseur = attacker.name;

    const dialog = await RdDRoll.create(actor, rollData,
      {
        html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-defense-possession.html',
        options: { height: 400 }
      },
      {
        name: 'conjurer',
        label: 'Conjurer une Possession',
        callbacks: [
          { action: async r => this.resultConjuration(r) }
        ]
      }
    );
    dialog.render(true);
  }

  /* -------------------------------------------- */
  static _onRollPossession( rollData, isSuccess ) {
    let possession = rollData.possession;
    possession.isSuccess = isSuccess;
    this.updateEtatPossession( possession);
    RdDResolutionTable.displayRollData(rollData, this, 'chat-resultat-possession.html');
  }

  /* -------------------------------------------- */
  static async managePosession(attacker, competence ) {    
    
    const target = RdDCombat.getTarget();
    if (target == undefined) {
      ui.notifications.warn((game.user.targets?.size ?? 0) > 1
        ? "Vous devez choisir <strong>une seule</strong> cible à posséder!"
        : "Vous devez choisir une cible à posséder!");
      return;
    }    
    
    const defender = target.actor;
    let possession = this.searchPossessionFromEntite( attacker, defender);
    if ( !possession) {
      possession = this.createPossession(attacker, defender);
    }

    this.updateEtatPossession(possession);
    let rollData = {
      competence: competence,
      possession: possession,
      possede: defender.name,
      possesseur: attacker.name,
      attackerId: attacker.data._id,
      defenderId: defender.data._id,
      mode: "possession"
    };
    if ( attacker.isCreature()) {
      RdDItemCompetenceCreature.setRollDataCreature(rollData);
    }
    console.log("Creation de possession2", attacker, rollData);

    const dialog = await RdDRoll.create( attacker, rollData,
      {
        html: 'systems/foundryvtt-reve-de-dragon/templates/dialog-roll-competence.html',
        options: { height: 540 }
      }, {
      name: 'jet-possession',
      label: 'Possession: ',
      callbacks: [
        { condition: r => (r.rolled.isSuccess), action: r => this._onRollPossession(r, true) },
        { condition: r => (r.rolled.isEchec), action: r => this._onRollPossession(r, false) },
      ]
    });
    dialog.render(true);
  }

  /* -------------------------------------------- */
  static async createPossession( attacker, defender ) {
    let posessionData = {
      name: "Possession en cours", type: 'possession',
      img: "systems/foundryvtt-reve-de-dragon/icons/entites/possession2.webp",
      data: { description: "", possede: false, possessionid: randomID(16), possesseurid: attacker.data._id, possedeid: defender.data._id, date: 0 }
    }
    await attacker.createEmbeddedDocuments('Item', [posessionData])
    let poss = await defender.createEmbeddedDocuments('Item', [posessionData])
    return duplicate(poss[0]);
  }

}