import { SYSTEM } from "../../config/system.mjs"
import { buildSharedSelectOptions, numericOptions } from "./select-options.mjs"
import { enrichHTMLFields } from "./rich-text.mjs"

const { HandlebarsApplicationMixin } = foundry.applications.api

export default class MGNEItemSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {
  static DEFAULT_OPTIONS = {
    classes: ["mgne", "item-sheet"],
    position: {
      width: 720,
      height: "auto",
    },
    window: {
      resizable: true,
    },
    form: {
      submitOnChange: true,
    },
    actions: {
      editImage: MGNEItemSheet.onEditImage,
    },
  }

  async _prepareContext() {
    const selectOptions = buildSharedSelectOptions()
    const systemFields = this.document.system.schema.fields
    if (this.document.type === "armor") selectOptions.penalties = numericOptions(0, 6, this.document.system.penalty)
    if (this.document.type === "shield") selectOptions.penalties = numericOptions(0, 4, this.document.system.penalty)

    return {
      fields: this.document.schema.fields,
      systemFields,
      item: this.document,
      system: this.document.system,
      source: this.document.toObject(),
      config: SYSTEM,
      enrichedFields: await enrichHTMLFields(this.document.system, systemFields),
      isEditable: this.isEditable,
      selectOptions,
    }
  }

  static async onEditImage(_event, target) {
    const attr = target.dataset.edit
    const current = foundry.utils.getProperty(this.document, attr)
    const picker = new FilePicker({
      current,
      type: "image",
      callback: path => this.document.update({ [attr]: path }),
      top: this.position.top + 40,
      left: this.position.left + 10,
    })
    return picker.browse()
  }
}
