import { RdDBaseActorReveSheet } from "./base-actor-reve-sheet.js";
import { RdDSheetUtility } from "../rdd-sheet-utility.js";
import { RdDUtility } from "../rdd-utility.js";

export class RdDActorEntiteSheet extends RdDBaseActorReveSheet {

  /** @override */
  static get defaultOptions() {
    return foundry.utils.mergeObject(RdDBaseActorReveSheet.defaultOptions, {
      template: "systems/foundryvtt-reve-de-dragon/templates/actor-entite-sheet.html",
      width: 640, height: 720,
    }, { inplace: false })
  }

  async getData() {
    let formData = await super.getData();
    formData.resonances = this.actor.system.sante.resonnance.actors.map(actorId => game.actors.get(actorId))
      .map(actor => { return { id: actor.id, name: actor.name, img: actor.img } })
    return formData
  }

  /* -------------------------------------------- */
  /** @override */
  activateListeners(html) {
    super.activateListeners(html);

    // Everything below here is only needed if the sheet is editable
    if (!this.options.editable) return;

    // On competence change
    this.html.find('.creature-carac').change(async event => {
      let compName = event.currentTarget.attributes.compname.value;
      this.actor.updateCreatureCompetence(compName, "carac_value", parseInt(event.target.value));
    });
    this.html.find('.creature-niveau').change(async event => {
      let compName = event.currentTarget.attributes.compname.value;
      this.actor.updateCreatureCompetence(compName, "niveau", parseInt(event.target.value));
    });
    this.html.find('.creature-dommages').change(async event => {
      let compName = event.currentTarget.attributes.compname.value;
      this.actor.updateCreatureCompetence(compName, "dommages", parseInt(event.target.value));
    });
    this.html.find('.resonance-delete').click(async event => {
      const li = RdDSheetUtility.getEventElement(event);
      const actorId = li.data("actor-id");
      if (actorId) {
        const actorResonance = game.actors.get(actorId);
        RdDUtility.confirmSubActeurDelete(this, actorResonance, li, () => {
          console.log('Delete : ', actorId);
          this.deleteSubActeur(actorId);
          RdDUtility.slideOnDelete(this, li);
        });
      }
    });
  }

  async _onDropActor(event, dragData) {
    const dropActor = fromUuidSync(dragData.uuid)
    await this.actor.setEntiteReveAccordee(dropActor)
    super._onDropActor(event, dragData)
  }

  async deleteSubActeur(actorId) {
    let newResonances = this.actor.system.sante.resonnance.actors.filter(id => id != actorId);
    await this.actor.update({ 'system.sante.resonnance.actors': newResonances }, { renderSheet: false });
  }
}