import PlaceableTab from "./placeable-tab.mjs";

/**
 * The Drawing-specific placeables tab.
 * @extends {PlaceableTab}
 */
export default class DrawingTab extends PlaceableTab {
  /** @override */
  static DEFAULT_OPTIONS = {
    actions: {
      selectGroup: DrawingTab.#onSelectGroup
    }
  };

  /** @override */
  static DIRECTORY_PARTIAL = "templates/sidebar/tabs/placeable/drawings.hbs";

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

  /** @override */
  _getEntryLabel(entry) {
    return entry.name || entry.text || entry.id;
  }

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

  /** @inheritDoc */
  async _prepareDirectoryContext(context, options) {
    context = await super._prepareDirectoryContext(context, options);
    const noAuthor = [];
    const groups = {};
    for ( const entry of context.entries ) {
      const { author } = entry;
      if ( author ) {
        const { color, id, name: label } = author;
        const group = groups[id] ??= { color, id, label, entries: [] };
        group.entries.push(entry);
      }
      else noAuthor.push(entry);
    }
    context.groups = Object.values(groups);
    if ( noAuthor.length ) context.groups.unshift({ label: _loc("SIDEBAR.PLACEABLES.Categories.NoAuthor"), entries: noAuthor });
    return context;
  }

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

  /** @inheritDoc */
  async _prepareEntry(entry, context) {
    context = await super._prepareEntry(entry, context);
    context.author = entry.author;
    return context;
  }

  /* -------------------------------------------- */
  /*  Event Listeners & Handlers                  */
  /* -------------------------------------------- */

  /**
   * Handle selecting a group of objects.
   * @this {DrawingTab}
   * @param {PointerEvent} event  The triggering event.
   * @param {HTMLElement} target  The action target.
   */
  static #onSelectGroup(event, target) {
    const { authorId } = target.closest("[data-author-id]").dataset;
    const [release, control] = this.layer.placeables.partition(d => {
      return (!authorId && !d.document.author) || (d.document.author.id === authorId);
    });
    if ( !event.shiftKey ) release.forEach(d => d.release({ renderSidebar: false }));
    control.forEach(d => d.control({ renderSidebar: false, releaseOthers: false }));
    ui.placeables.render();
    if ( game.activeTool === "select" ) ui.placeablesPalette?.render();
  }
}
