import { RdDRencontre } from "./item-rencontre.js";
import { RdDItemSheet } from "./item-sheet.js";

export class RdDRencontreItemSheet extends RdDItemSheet {
  
  static get ITEM_TYPE() { return "rencontre" };

  static get defaultOptions() {
    return mergeObject(super.defaultOptions, {
      tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "carac" }]
    });
  }

  /* -------------------------------------------- */
  /** @override */
  setPosition(options = {}) {
    const position = super.setPosition(options);
    const sheetHeader = this.element.find(".sheet-header");
    const sheetBody = this.element.find(".sheet-body");
    sheetBody.css("height", position.height - sheetHeader[0].clientHeight)
    return position;
  }

  /* -------------------------------------------- */
  async getData() {
    const formData = await super.getData();
    mergeObject(formData, {
      effets: {
        succes: {
          liste: RdDRencontre.getEffetsSucces(),
          select: RdDRencontre.mapEffets(this.item.system.succes.effets)
        },
        echec: {
          liste: RdDRencontre.getEffetsEchec(),
          select: RdDRencontre.mapEffets(this.item.system.echec.effets)
        }
      }
    });
    return formData;
  }

  /* -------------------------------------------- */
  /** @override */
  activateListeners(html) {
    super.activateListeners(html);
    if (!this.options.editable) return;
    this.html.find("a.effet-add").click(event => this.onAddEffet(event));
    this.html.find("a.effet-delete").click(event => this.onDeleteEffet(event));
  }

  async onAddEffet(event) {
    const resultat = this.html.find(event.currentTarget)?.data("effet-resultat");
    const keyEffets = `system.${resultat}.effets`;

    const code = this.html.find(event.currentTarget)?.data("effet-code");
    const liste = RdDRencontre.getListeEffets(this.item, resultat);
    liste.push(code);

    await this._updateEffetsRencontre(keyEffets, liste);
  }

  async onDeleteEffet(event) {
    const resultat = this.html.find(event.currentTarget)?.data("effet-resultat");
    const keyEffets = `system.${resultat}.effets`;
    
    const pos = this.html.find(event.currentTarget)?.data("effet-pos");
    const liste = RdDRencontre.getListeEffets(this.item, resultat);
    liste.splice(pos, 1);
    
    await this._updateEffetsRencontre(keyEffets, liste);
  }
  
  async _updateEffetsRencontre(key, liste) {
    const updates = {};
    updates[key] = liste;
    this.item.update(updates);
  }
}