/* -------------------------------------------- */
import { MaleficesUtility } from "./malefices-utility.js";

const { HandlebarsApplicationMixin, ApplicationV2 } = foundry.applications.api

/* -------------------------------------------- */
export class MaleficesCharacterSummary extends HandlebarsApplicationMixin(ApplicationV2) {

  /* -------------------------------------------- */
  static DEFAULT_OPTIONS = {
    id: "malefices-character-summary",
    classes: ["MaleficesDialog"],
    window: { title: "Résumé des Personnages", resizable: true },
    position: { width: 960, height: "auto" },
    dragDrop: [{ dragSelector: null, dropSelector: ".character-summary-container" }],
  }

  static PARTS = {
    form: { template: "systems/fvtt-malefices/templates/dialogs/character-summary.hbs" }
  }

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

  /* -------------------------------------------- */
  updatePCSummary() {
    if (this.element?.isConnected) {
      this.render({ force: true })
    }
  }

  /* -------------------------------------------- */
  static ready() {
    if (!game.user.isGM) {
      return
    }
    game.system.malefices.charSummary = new MaleficesCharacterSummary()
  }

  /* -------------------------------------------- */
  constructor(options = {}) {
    super(options)
    const saved = game.settings.get("world", "character-summary-data")
    this.extraList = saved.extraList ?? saved.npcList ?? []
  }

  /* -------------------------------------------- */
  async _prepareContext(_options) {
    const pcs = game.actors.filter(ac => ac.type === "personnage" && ac.hasPlayerOwner)
    const extras = []
    const validList = []
    for (const actorId of this.extraList) {
      const actor = game.actors.get(actorId)
      if (actor) { extras.push(actor); validList.push(actorId) }
    }
    if (validList.length !== this.extraList.length) {
      this.extraList = validList
      this._persist()
    }
    return { pcs, extras, config: game.system.malefices.config }
  }

  /* -------------------------------------------- */
  _onRender(_context, _options) {
    const el = this.element

    el.querySelectorAll('.actor-open').forEach(a => {
      a.addEventListener('click', event => {
        const li = event.currentTarget.closest('.item')
        const actor = game.actors.get(li.dataset.actorId)
        actor?.sheet.render(true)
      })
    })

    el.querySelectorAll('.summary-roll').forEach(a => {
      a.addEventListener('click', event => {
        const li = event.currentTarget.closest('.item')
        const actor = game.actors.get(li.dataset.actorId)
        const key = event.currentTarget.dataset.key
        actor?.rollAttribut(key)
      })
    })

    el.querySelectorAll('.actor-delete').forEach(a => {
      a.addEventListener('click', event => {
        const li = event.currentTarget.closest('.item')
        this.extraList = this.extraList.filter(id => id !== li.dataset.actorId)
        this._persist()
        this.render({ force: true })
      })
    })

    const dropZone = el.querySelector('.character-summary-container')
    if (dropZone) {
      dropZone.addEventListener('dragover', ev => ev.preventDefault())
      dropZone.addEventListener('drop', ev => { ev.stopPropagation(); this._onDrop(ev) })
    }
  }

  /* -------------------------------------------- */
  _canDragDrop(_selector) { return true }

  /* -------------------------------------------- */
  _persist() {
    const saved = game.settings.get("world", "character-summary-data")
    game.settings.set("world", "character-summary-data", { ...saved, extraList: this.extraList })
  }

  /* -------------------------------------------- */
  _saveAndRefresh() {
    this.render({ force: true })
  }

  /* -------------------------------------------- */
  async _onDrop(event) {
    try {
      const dataItem = JSON.parse(event.dataTransfer.getData('text/plain'))
      const actor = fromUuidSync(dataItem.uuid)
      if (actor && !this.extraList.includes(actor.id)) {
        this.extraList.push(actor.id)
        this._persist()
        this.render({ force: true })
      }
    } catch(e) { /* not a valid drag payload */ }
  }

}