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

import { getGame } from '../../helpers';

export const registerActiveEffectFunctionality = () => {
  Hooks.on('createActiveEffect', onActiveEffectChanged);
  Hooks.on('updateActiveEffect', onActiveEffectChanged);
  Hooks.on('deleteActiveEffect', onActiveEffectChanged);
};

const onActiveEffectChanged = (activeEffect) => {
  const game = getGame();
  const parent = activeEffect.parent;
  const actorId = parent?.id;
  if (!(parent instanceof Actor) || actorId === null || actorId === undefined) return;

  const statusId = activeEffect.getFlag('core', 'statusId');

  if (statusId === CONFIG.Combat.defeatedStatusId) {
    const relevantCombats = game.combats?.filter((combat) => combat.getCombatantByActor(actorId) !== undefined) ?? [];

    for (const combat of relevantCombats) {
      combat.setupTurns();
      if (combat === game.combat) {
        ui.combat?.render();
      }
    }
  }
};
