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

import { DS4 } from "../config";
import { isCheck } from "../documents/actor/actor-data-properties-base";
import { notifications } from "../ui/notifications";
import { getGame } from "../utils/utils";
import { getActiveActorAndToken } from "./helpers";

/**
 * Creates a macro from a check drop.
 * Get an existing roll check macro if one exists, otherwise create a new one.
 * @param {object} data The check drop data
 * @param {string} slot The hotbar slot to use
 * @returns {Promise<void>} A promise that resolves when the macro has been created.
 */
export async function createRollCheckMacro(data, slot) {
  if (!("data" in data) || typeof data.data !== "string" || !isCheck(data.data)) {
    return notifications.warn(getGame().i18n.localize("DS4.WarningInvalidCheckDropped"));
  }
  const macro = await getOrCreateRollCheckMacro(data.data);
  await getGame().user?.assignHotbarMacro(macro ?? null, slot);
}

/**
 * @param {import("../documents/actor/actor-data-properties-base").Check} check The name of the check to perform
 * @returns {Promise<Macro|undefined>} A promise that resolves to the created macro
 */
async function getOrCreateRollCheckMacro(check) {
  const command = `game.ds4.macros.rollCheck("${check}");`;

  const existingMacro = getGame().macros?.find((m) => m.name === DS4.i18n.checks[check] && m.command === command);
  if (existingMacro) {
    return existingMacro;
  }

  return Macro.create(
    {
      command,
      name: DS4.i18n.checks[check],
      type: "script",
      img: DS4.icons.checks[check],
      flags: { "ds4.checkMacro": true },
    },
    { renderSheet: false },
  );
}

/**
 * Executes the roll check macro for the given check.
 * @param {import("../documents/actor/actor-data-properties-base").Check} check The name of the check to perform
 * @returns {Promise<void>} A promise that resolves once the check has been performed.
 */
export async function rollCheck(check) {
  const { actor, token } = getActiveActorAndToken();
  if (!actor) {
    return notifications.warn(getGame().i18n.localize("DS4.WarningMustControlActorToUseRollCheckMacro"));
  }

  return actor.rollCheck(check, { speaker: { token } }).catch((e) => notifications.error(e, { log: true }));
}
