import { RdDBaseActorSheetV2 } from "./base-actor-sheet.mjs"
import { RdDItem } from "../../item.js"
import { ACTOR_TYPES } from "../../constants.js"

export class RdDCommerceSheetV2 extends RdDBaseActorSheetV2 {

  static TYPE = ACTOR_TYPES.commerce

  static DEFAULT_OPTIONS = Object.assign({}, RdDBaseActorSheetV2.DEFAULT_OPTIONS, {
    position: { width: 600, height: 720 },
  })

  static PARTS = {
    form: { template: "systems/foundryvtt-reve-de-dragon/templates/actor/commerce-actor-sheet.hbs" },
  }

  get title() {
    if (this.actor.token && this.actor.token !== this.actor.prototypeToken) {
      return this.actor.token.name
    }
    return super.title
  }

  async _prepareContext() {
    const ctx = await super._prepareContext()
    if (this.actor.token && this.actor.token !== this.actor.prototypeToken) {
      foundry.utils.mergeObject(ctx, {
        title: this.actor.token.name,
        token: { img: this.actor.token.texture.src },
      }, { overwrite: true })
    }
    return ctx
  }

  async _onRender(context, options) {
    await super._onRender(context, options)
    if (!this.isEditable) return

    this.html.find("input.item-quantite").change(async event => {
      const newQuantite = Math.max(0, Number.parseInt(this.html.find(event.currentTarget).val()))
      await this._getItem(event)?.update({ "system.quantite": newQuantite })
    })
    this.html.find("input.item-cout").change(async event => {
      const newCout = Math.max(0, Number(this.html.find(event.currentTarget).val()))
      await this._getItem(event)?.update({ "system.cout": newCout })
    })
  }

  _getTypesInventaire() {
    return RdDItem.getItemTypesInventaire("all")
  }
}
