export class DialogStress extends Dialog {

  static async distribuerStress() {
    const dialogData = {
      motif: "Motif",
      stress: 10,
      immediat: false,
      actors: game.actors.filter(actor => actor.isPersonnageJoueur())
        .map(actor => ({
            id: actor.id,
            name: actor.name,
            selected: true
          })
        )
    };

    const html = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/sommeil/dialog-stress.html", dialogData);
    new DialogStress(dialogData, html)
      .render(true);
  }

  constructor(dialogData, html) {
    const options = { classes: ["DialogStress"],
      width: 400,
      height: 'fit-content',
      'z-index': 99999
    };
    const conf = {
      title: "Donner du stress",
      content: html,
      buttons: {
        stress: { label: "Stress !", callback: it => { this.onStress(); } }
      }
    };
    super(conf, options);
    this.dialogData = dialogData;
  }

  activateListeners(html) {
    super.activateListeners(html);
    this.html = html;
    this.html.find("input.select-actor").change((event) => this.onSelectActor(event));
  }

  async onStress() {
    const motif = this.html.find("form.rdddialogstress input[name='motif']").val();
    const stress = Number(this.html.find("form.rdddialogstress input[name='stress']").val());
    const compteur = (this.html.find("form.rdddialogstress input[name='immediat']").prop("checked")) ? 'experience' : 'stress';

    this.dialogData.actors.filter(it => it.selected)
      .map(it => game.actors.get(it.id))
      .forEach(async actor => await actor.distribuerStress(compteur, stress, motif));
  }

  async onSelectActor(event) {
    const actorId = this.html.find(event.currentTarget)?.data("actor-id");
    const actor = this.dialogData.actors.find(it => it.id == actorId);
    if (actor) {
      actor.selected = event.currentTarget.checked;
    }
  }
}