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

/**
 * Tests if the given `value` is truthy.
 *
 * If it is not truthy, an {@link Error} is thrown, which depends on the given `message` parameter:
 * - If `message` is a string`, it is used to construct a new {@link Error} which then is thrown.
 * - If `message` is an instance of {@link Error}, it is thrown.
 * - If `message` is `undefined`, an {@link Error} with a default message is thrown.
 * @param {unknown} value   The value to check for truthyness
 * @param {string | Error} [message] An error message to use when the check fails
 * @returns {asserts value}
 */
export function enforce(value, message) {
  if (!value) {
    if (!message) {
      message =
        getGameSafe()?.i18n.localize("DS4.ErrorUnexpectedError") ??
        "There was an unexpected error in the Dungeonslayers 4 system. For more details, please take a look at the console (F12).";
    }
    throw message instanceof Error ? message : new Error(message);
  }
}

/**
 * A wrapper that returns the canvas, if it is ready.
 * @throws if the canvas is not ready yet
 * @returns {Canvas}
 */
export function getCanvas() {
  enforce(canvas instanceof Canvas && canvas.ready, getGame().i18n.localize("DS4.ErrorCanvasIsNotInitialized"));
  return canvas;
}

/**
 * A wrapper that returns the game, if it already exists.
 * @throws {Error} if the game is not ready yet
 * @returns {Game}
 */
export function getGame() {
  enforce(game instanceof Game, "Game is not initialized yet.");
  return game;
}

/**
 * A wrapper that returns the game, or `undefined` if it doesn't exist yet
 * @returns {Game | undefined}
 */
export function getGameSafe() {
  return game instanceof Game ? game : undefined;
}

/**
 * A wrapper that returns `ui.notifications`, or `undefined` if it doesn't exist yet
 * @returns {Notifications | undefined}
 */
export function getNotificationsSafe() {
  return ui.notifications instanceof Notifications ? ui.notifications : undefined;
}
