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

import { getGame } from "../utils/utils";

/**
 * Disable elements in the given form that match the selector returned for overridden properties.
 * @param {HTMLElement | null} form The form in which to disable fields
 * @param {Record<string, unknown>} overrides The set of overrides of the underlying document
 * @param {(key: string) => string} selector A function that generates a selector, based on a property key
 */
export function disableOverriddenFields(form, overrides, selector) {
  const inputs = ["INPUT", "SELECT", "TEXTAREA", "BUTTON"];
  const titleAddition = `(${getGame().i18n.localize("DS4.TooltipNotEditableDueToEffects")})`;

  for (const key of Object.keys(foundry.utils.flattenObject(overrides))) {
    const elements = form?.querySelectorAll(selector(key));
    elements?.forEach((element) => {
      if (inputs.includes(element.tagName) && !element.hasAttribute("disabled")) {
        element.setAttribute("disabled", "");
        const title = element.getAttribute("title");
        const newTitle = title === null ? titleAddition : `${title} ${titleAddition}`;
        element.setAttribute("title", newTitle);
      }
    });
  }
}
