// SPDX-FileCopyrightText: 2021 Johannes Loher
// SPDX-FileCopyrightText: 2021 Oliver Rümpelein
// SPDX-FileCopyrightText: 2021 Gesina Schwalbe
//
// SPDX-License-Identifier: MIT

import { DS4 } from "../config";
import { DS4ActiveEffect } from "../documents/active-effect";
import { enforce, getGame } from "../utils/utils";
import { disableOverriddenFields } from "./sheet-helpers";

/**
 * The Sheet class for DS4 Items
 */
export class DS4ItemSheet extends ItemSheet {
  /** @override */
  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      classes: ["sheet", "ds4-item-sheet"],
      height: 400,
      scrollY: [".ds4-sheet-body"],
      tabs: [{ navSelector: ".ds4-sheet-tab-nav", contentSelector: ".ds4-sheet-body", initial: "description" }],
      width: 540,
    });
  }

  /** @override */
  get template() {
    const basePath = "systems/ds4/templates/sheets/item";
    return `${basePath}/${this.item.type}-sheet.hbs`;
  }

  /** @override */
  async getData(options = {}) {
    const superContext = await super.getData(options);
    superContext.data.system.description = await TextEditor.enrichHTML(superContext.data.system.description, {
      async: true,
    });
    const context = {
      ...superContext,
      config: DS4,
      isOwned: this.item.isOwned,
      actor: this.item.actor,
    };
    return context;
  }

  /** @override */
  _getSubmitData(updateData = {}) {
    const data = super._getSubmitData(updateData);
    // Prevent submitting overridden values
    const overrides = foundry.utils.flattenObject(this.item.overrides);
    for (const k of Object.keys(overrides)) {
      delete data[k];
    }
    return data;
  }

  /** @override */
  setPosition(options = {}) {
    const position = super.setPosition(options);
    if (position) {
      const sheetBody = this.element.find(".sheet-body");
      const bodyHeight = position.height - 192;
      sheetBody.css("height", bodyHeight);
    }

    return position;
  }

  /**
   * @override
   * @param {JQuery} html
   */
  activateListeners(html) {
    super.activateListeners(html);

    if (!this.options.editable) return;

    html.find(".control-effect").on("click", this.onControlEffect.bind(this));

    disableOverriddenFields(this.form, this.item.overrides, (key) => `[name="${key}"]`);
  }

  /**
   * Handles a click on an element of this sheet to control an embedded effect of the item corresponding to this
   * sheet.
   *
   * @param {JQuery.ClickEvent} event The originating click event
   * @protected
   */
  onControlEffect(event) {
    event.preventDefault();
    const a = event.currentTarget;
    switch (a.dataset["action"]) {
      case "create":
        return this.onCreateEffect();
      case "edit":
        return this.onEditEffect(event);
      case "delete":
        return this.onDeleteEffect(event);
    }
  }

  /**
   * Creates a new embedded effect.
   * @protected
   */
  onCreateEffect() {
    DS4ActiveEffect.createDefault(this.item);
  }

  /**
   * Opens the sheet of the embedded effect corresponding to the clicked element.
   *
   * @param {JQuery.ClickEvent} event The originating click event
   * @porotected
   */
  onEditEffect(event) {
    const id = $(event.currentTarget)
      .parents(embeddedDocumentListEntryProperties.ActiveEffect.selector)
      .data(embeddedDocumentListEntryProperties.ActiveEffect.idDataAttribute);
    const effect = this.item.effects.get(id);
    enforce(effect, getGame().i18n.format("DS4.ErrorItemDoesNotHaveEffect", { id, item: this.item.name }));
    effect.sheet?.render(true);
  }

  /**
   * Deletes the embedded item corresponding to the clicked element.
   *
   * @param {JQuery.ClickEvent} event The originating click event
   * @protected
   */
  onDeleteEffect(event) {
    const li = $(event.currentTarget).parents(embeddedDocumentListEntryProperties.ActiveEffect.selector);
    const id = li.data(embeddedDocumentListEntryProperties.ActiveEffect.idDataAttribute);
    this.item.deleteEmbeddedDocuments("ActiveEffect", [id]);
    li.slideUp(200, () => this.render(false));
  }
}

/**
 * This object contains information about specific properties embedded document list entries for each different type.
 */
const embeddedDocumentListEntryProperties = Object.freeze({
  ActiveEffect: {
    selector: ".effect",
    idDataAttribute: "effectId",
  },
});
