/* -------------------------------------------- */
const { HandlebarsApplicationMixin } = foundry.applications.api

/* -------------------------------------------- */
export class EcrymeCharacterSummary extends HandlebarsApplicationMixin(foundry.applications.api.ApplicationV2) {

  /* -------------------------------------------- */
  static DEFAULT_OPTIONS = {
    id: "ecryme-character-summary",
    classes: ["fvtt-ecryme", "dialog"],
    position: { width: 920 },
    window: { title: "ECRY.ui.charactersummary", resizable: true },
    actions: {
      actorOpen:   EcrymeCharacterSummary.#onActorOpen,
      summaryRoll: EcrymeCharacterSummary.#onSummaryRoll,
      actorDelete: EcrymeCharacterSummary.#onActorDelete,
    },
  }

  /* -------------------------------------------- */
  static PARTS = {
    content: { template: "systems/fvtt-ecryme/templates/dialogs/character-summary.hbs" },
  }

  /* -------------------------------------------- */
  constructor(options = {}) {
    super(options)
    this.settings = game.settings.get("fvtt-ecryme", "character-summary-data")
  }

  /* -------------------------------------------- */
  static displayPCSummary() {
    if (game.user.isGM) {
      game.ecryme.charSummary.render(true)
    } else {
      ui.notifications.info("Commande /summary réservée au MJ !")
    }
  }

  /* -------------------------------------------- */
  updatePCSummary() {
    if (this.rendered) {
      this.render()
    }
  }

  /* -------------------------------------------- */
  static ready() {
    if (!game.user.isGM) {
      return
    }
    let charSummary = new EcrymeCharacterSummary()
    game.ecryme.charSummary = charSummary
  }

  /* -------------------------------------------- */
  async _prepareContext() {
    let pcs = game.actors.filter(ac => ac.type == "pc" && ac.hasPlayerOwner)
    let npcs = []
    let newList = []
    let toUpdate = false
    for (let actorId of this.settings.npcList) {
      let actor = game.actors.get(actorId)
      if (actor) {
        npcs.push(actor)
        newList.push(actorId)
      } else {
        toUpdate = true
      }
    }
    if (toUpdate) {
      this.settings.npcList = newList
      game.settings.set("fvtt-ecryme", "character-summary-data", this.settings)
    }
    return {
      pcs,
      npcs,
      config: game.ecryme.config,
    }
  }

  /* -------------------------------------------- */
  updateNPC() {
    game.settings.set("fvtt-ecryme", "character-summary-data", this.settings)
    this.close()
    setTimeout(() => this.render(true), 500)
  }

  /* -------------------------------------------- */
  _onDragOver(event) {
    event.preventDefault()
  }

  /* -------------------------------------------- */
  _onDrop(event) {
    let data
    try { data = JSON.parse(event.dataTransfer.getData('text/plain')) } catch(e) { return }
    let actor = fromUuidSync(data.uuid)
    if (actor) {
      this.settings.npcList.push(actor.id)
      this.updateNPC()
    } else {
      ui.notifications.warn("Pas d'acteur trouvé")
    }
  }

  /* -------------------------------------------- */
  _onRender(context, options) {
    super._onRender(context, options)
    this.element.addEventListener("dragover", this._onDragOver.bind(this))
    this.element.addEventListener("drop",     this._onDrop.bind(this))
  }

  /* -------------------------------------------- */
  static #onActorOpen(event, target) {
    const actorId = target.closest("[data-actor-id]").dataset.actorId
    game.actors.get(actorId)?.sheet.render(true)
  }

  /* -------------------------------------------- */
  static #onSummaryRoll(event, target) {
    const actorId = target.closest("[data-actor-id]").dataset.actorId
    const key     = target.dataset.key
    game.actors.get(actorId)?.rollAttribut(key)
  }

  /* -------------------------------------------- */
  static #onActorDelete(event, target) {
    const actorId = target.closest("[data-actor-id]").dataset.actorId
    this.settings.npcList = this.settings.npcList.filter(id => id !== actorId)
    this.updateNPC()
  }

}