// SPDX-FileCopyrightText: 2021 Johannes Loher
//
// SPDX-License-Identifier: MIT

export const registerCombatTrackerFunctionality = () => {
  CONFIG.ui.combat = CombatTrackerMixin(CONFIG.ui.combat);
};

/**
 * Enhance a combat tracker class with functionality for Tickwerk.
 * @param {typeof CombatTracker} BaseCombatTracker The combat tracker class to enhance
 * @returns The enhanced combat tracker class
 */
const CombatTrackerMixin = (BaseCombatTracker) => {
  return class TickwerkCombatTracker extends BaseCombatTracker {
    /** @override */
    static get defaultOptions() {
      return foundry.utils.mergeObject(super.defaultOptions, {
        template: 'modules/tickwerk/templates/combat-tracker.hbs',
      });
    }

    /** @override */
    async getData(options) {
      const data = await super.getData(options);
      return {
        ...data,
        turns: data.turns.map((turn) => ({ ...turn, waiting: this.viewed?.combatants.get(turn.id)?.waiting })),
      };
    }

    /** @override */
    activateListeners(html) {
      super.activateListeners(html);
      html.find('.combatant-control[data-control="toggleWaiting"]').on('click', this._onToggleWaiting.bind(this));
    }

    /**
     * Handle clicks on the Combatant waiting control button.
     * @param {JQuery.ClickEvent} event The originating click event
     */
    _onToggleWaiting(event) {
      event.preventDefault();
      event.stopPropagation();
      const button = event.currentTarget;
      const li = button.closest('.combatant');
      const combat = this.viewed;
      const combatant = combat?.combatants.get(li.dataset.combatantId);
      combatant?.toggleWaiting();
    }
  };
};
