import { TEMPLATE_DESCRIPTION } from "../../common/_module.mjs";
import { ITEM_TYPES } from "../../constants.js";
import RdDItemBaseSheet from "./common-item-sheet.mjs";

export default class RdDTacheSheet extends RdDItemBaseSheet {
  static get ITEM_TYPE() { return ITEM_TYPES.tache; }
  static get TEMPLATES() { return [TEMPLATE_DESCRIPTION]; }

  static DEFAULT_OPTIONS = Object.assign({},
    RdDItemBaseSheet.DEFAULT_OPTIONS,
    { classes: ["fvtt-rdd", "item", "tache"], position: { width: 448 }, window: { contentClasses: ["tache-content"] } });

  static PARTS = {
    main: { template: "systems/foundryvtt-reve-de-dragon/templates/sheets/item/tache.hbs" },
  };

  async _prepareContext() {
    const ctx = await super._prepareContext()
    const item = this.document

    if (item.system.tacheCommuneId) {
      ctx.tacheCommune = game.items.get(item.system.tacheCommuneId)
      if (ctx.tacheCommune) {
        ctx.isPartagee = true
        ctx.disabled = !!item.parent
        ctx.communeName = ctx.tacheCommune.name
      }
    } else if (!item.parent) {
      ctx.estCommune = item.system.tacheCommuneId === item.id
    }
    return ctx
  }

  async _onRender(context, options) {
    await super._onRender(context, options)

    this.element.querySelector('.is-tache-partagee')?.addEventListener('change', async e => {
      const checked = e.currentTarget.checked
      if (!this.document.parent) {
        await this.document.update({ 'system.tacheCommuneId': checked ? this.document.id : '' })
        this.render()
      }
    })
  }
}
