const { HandlebarsApplicationMixin } = foundry.applications.api
import { SYSTEM_RDD } from "../../constants.js"
import { Misc } from "../../misc.js"
import { RdDSheetUtility } from "../../rdd-sheet-utility.js";


export default class RdDItemBaseSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {

  static preloadHandlebars(...templatesList) {
    const handlebars = ["systems/foundryvtt-reve-de-dragon/templates/sheets/item/common/header.hbs"]
    templatesList.forEach(templates =>
      templates.forEach(t =>
        t.handlebars().forEach(h => handlebars.push(h))
      )
    )
    loadTemplates(Misc.distinct(handlebars))
  }

  static register(sheetClass) {
    const itemType = sheetClass.ITEM_TYPE
    foundry.documents.collections.Items.registerSheet(SYSTEM_RDD, sheetClass, {
      label: Misc.typeName('Item', itemType),
      types: [itemType],
      makeDefault: true
    })
  }

  static registerAll(...sheetClasses) {
    const handlebars = ["systems/foundryvtt-reve-de-dragon/templates/sheets/item/common/header.hbs"]
    sheetClasses.forEach(sheetClass => {
      sheetClass.TEMPLATES.forEach(t =>
        t.handlebars().forEach(h => handlebars.push(h))
      )
      const itemType = sheetClass.ITEM_TYPE
      foundry.documents.collections.Items.registerSheet(SYSTEM_RDD, sheetClass, {
        label: Misc.typeName('Item', itemType),
        types: [itemType],
        makeDefault: true
      })
    })
    foundry.applications.handlebars.loadTemplates(Misc.distinct(handlebars))
  }

  static get ITEM_TYPE() { return undefined }

  constructor(options = {}) {
    super(options)
  }

  static get TEMPLATES() { return [] }

  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-rdd", "item"],
    position: {
      width: 448,
      height: "auto",
    },
    form: {
      submitOnChange: true,
    },
    window: {
      resizable: true,
    },
    actions: {
      editImage: RdDItemBaseSheet._onEditImage,
      postToChat: RdDItemBaseSheet._onPostToChat,
      proposerVente: RdDItemBaseSheet._onProposerVente,
    }
  }

  /** @override */
  async _prepareContext() {
    const ctx = {
      item: this.document,
      options: RdDSheetUtility.getOptions(this.document, this.isEditable),
      fields: this.document.schema.fields,
      systemFields: this.document.system.schema.fields,
      system: this.document.system,
      source: this.document.toObject(),
      isEditable: this.isEditable,
      canVendre: this.document.isInventaire?.() && this.document.isVideOuNonConteneur?.(),
    }
    for (const tpl of this.constructor.TEMPLATES) {
      Object.assign(ctx, await tpl.prepareContext(this.document))
    }
    return ctx
  }

  // #region Actions

  /**
   * Handle changing a Document's image.
   *
   * @this RdDItemBaseSheet
   * @param {PointerEvent} event   The originating click event
   * @param {HTMLElement} target   The capturing HTML element which defined a [data-action]
   * @returns {Promise}
   * @private
   */
  static async _onEditImage(event, target) {
    const attr = target.dataset.edit
    const current = foundry.utils.getProperty(this.document, attr)
    const { img } = this.document.constructor.getDefaultArtwork?.(this.document.toObject()) ?? {}
    const fp = new FilePicker({
      current,
      type: "image",
      redirectToRoot: img ? [img] : [],
      callback: (path) => {
        this.document.update({ [attr]: path })
      },
      top: this.position.top + 40,
      left: this.position.left + 10,
    })
    return fp.browse()
  }

  static async _onPostToChat(event, target) {
    await this.document.postItemToChat()
  }

  static async _onProposerVente(event, target) {
    await this.document.proposerVente(1)
  }

  /** @override */
  async _renderFrame(options) {
    const frame = await super._renderFrame(options)
    const header = frame.querySelector(".window-header")
    if (header) {
      const closeBtn = header.querySelector("button[data-action=close]")
      const chatBtn = document.createElement("button")
      chatBtn.type = "button"
      chatBtn.className = "header-control icon fa-solid fa-comment"
      chatBtn.dataset.action = "postToChat"
      chatBtn.dataset.tooltip = "Poster dans le chat"
      chatBtn.ariaLabel = "Poster dans le chat"
      header.insertBefore(chatBtn, closeBtn)
      if (this.document.isInventaire?.() && this.document.isVideOuNonConteneur?.()) {
        const sellBtn = document.createElement("button")
        sellBtn.type = "button"
        sellBtn.className = "header-control icon fa-solid fa-comments-dollar"
        sellBtn.dataset.action = "proposerVente"
        sellBtn.dataset.tooltip = "Proposer à la vente"
        sellBtn.ariaLabel = "Proposer à la vente"
        header.insertBefore(sellBtn, chatBtn)
      }
    }
    return frame
  }

  // #endregion
}
