import JournalEntryPageCodeMirrorSheet from "./journal-entry-page-code-mirror-sheet.mjs";

/**
 * An Application responsible for displaying a single text-type JournalEntryPage Document, and editing it with an HTML
 * editor.
 * @extends JournalEntryPageCodeMirrorSheet
 */
export default class JournalEntryPageHTMLSheet extends JournalEntryPageCodeMirrorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    window: {
      icon: "fa-brands fa-html5"
    }
  };

  /** @inheritDoc */
  static EDIT_PARTS = {
    header: super.EDIT_PARTS.header,
    content: {
      classes: ["flex1", "flexcol"],
      template: "templates/journal/pages/html/edit.hbs"
    },
    footer: super.EDIT_PARTS.footer
  };

  /* -------------------------------------------- */
  /*  Rendering                                   */
  /* -------------------------------------------- */

  /** @inheritDoc */
  async _prepareContentContext(context, options) {
    await super._prepareContentContext(context, options);
    if ( !this.isView ) context.text.formatted = this.constructor.formatHTML(context.text.content);
  }

  /* -------------------------------------------- */
  /*  Form Submission                             */
  /* -------------------------------------------- */

  /** @inheritDoc */
  _prepareSubmitData(event, form, formData, updateData) {
    const submitData = super._prepareSubmitData(event, form, formData, updateData);
    const content = foundry.utils.getProperty(submitData, "text.content");
    if ( content ) foundry.utils.setProperty(submitData, "text.content", content.replace(/>\n+\s*</g, "><"));
    return submitData;
  }

  /* -------------------------------------------- */
  /*  Helpers                                     */
  /* -------------------------------------------- */

  /**
   * Auto-format an HTML string.
   * @param {string} html                       The HTML string.
   * @param {object} [options]
   * @param {string|number} [options.spaces=4]  The number of spaces to indent by, or a string to use as indentation.
   * @returns {string}
   */
  static formatHTML(html, { spaces=4 }={}) {
    if ( !html || !html.trim() ) return "";
    try {
      return foundry.utils.StringNode.fromString(html).toString(spaces);
    } catch(e) {
      console.warn("Failed to format HTML: ", e);
    }
    return "";
  }
}
