import ContextMenu from "./context-menu.mjs";

/**
 * @import {ContextMenuEntry, ContextMenuOptions} from "./context-menu.mjs";
 */

/**
 * @typedef _FilterMenuOptions
 * @property {() => ContextMenuEntry[]} [menuItems]  The menu item generator.
 */

/**
 * @typedef {ContextMenuOptions & _FilterMenuOptions} FilterMenuOptions
 */

/**
 * A specialized subclass of ContextMenu designed for displaying a menu of filter options.
 * @extends {ContextMenu}
 */
export default class FilterMenu extends ContextMenu {
  /**
   * @param {HTMLElement} container        The HTML element that contains the context menu targets.
   * @param {string} selector              A CSS selector which activates the context menu.
   * @param {FilterMenuOptions} [options]  Additional options to configure the context menu.
   */
  constructor(container, selector, options={}) {
    options = foundry.utils.mergeObject({
      eventName: "click", fixed: true, jQuery: false, relative: "target", closeOnSelect: false
    }, options);
    super(container, selector, [], options);
    this.#options = options;
  }

  /* -------------------------------------------- */

  /**
   * Configuration options.
   * @type {FilterMenuOptions}
   */
  #options;

  /* -------------------------------------------- */

  /** @inheritDoc */
  async _preRenderEntries(options={}) {
    await super._preRenderEntries(options);
    this.menuItems = this.#options.menuItems?.() ?? [];
  }

  /* -------------------------------------------- */
  /*  Factory Methods                             */
  /* -------------------------------------------- */

  /**
   * Retrieve the configured FilterMenu implementation.
   * @type {typeof FilterMenu}
   */
  static get implementation() {
    let Class = CONFIG.ux.FilterMenu;
    if ( !foundry.utils.isSubclass(Class, FilterMenu) ) {
      console.warn("Configured FilterMenu override must be a subclass of FilterMenu.");
      Class = FilterMenu;
    }
    return Class;
  }
}
