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

import { notifications } from "../ui/notifications";
import { getGame } from "../utils/utils";
import { getActiveActorAndToken } from "./helpers";

/**
 * Creates a macro from an item drop.
 * Get an existing roll item macro if one exists, otherwise create a new one.
 * @param itemData - The item data
 * @param slot     - The hotbar slot to use
 */
export async function createRollItemMacro(itemData: foundry.data.ItemData["_source"], slot: string): Promise<void> {
    const macro = await getOrCreateRollItemMacro(itemData);
    getGame().user?.assignHotbarMacro(macro ?? null, slot);
}

async function getOrCreateRollItemMacro(itemData: foundry.data.ItemData["_source"]): Promise<Macro | undefined> {
    const command = `game.ds4.macros.rollItem("${itemData._id}");`;

    const existingMacro = getGame().macros?.find((m) => m.name === itemData.name && m.data.command === command);
    if (existingMacro) {
        return existingMacro;
    }

    return Macro.create(
        {
            command,
            name: itemData.name,
            type: "script",
            img: itemData.img,
            flags: { "ds4.itemMacro": true },
        },
        { renderSheet: false },
    );
}

/**
 * Executes the roll item macro for the item associated to the given `itemId`.
 */
export async function rollItem(itemId: string): Promise<void> {
    const { actor, token } = getActiveActorAndToken();
    if (!actor) {
        return notifications.warn(getGame().i18n.localize("DS4.WarningMustControlActorToUseRollItemMacro"));
    }

    const item = actor.items.get(itemId);
    if (!item) {
        return notifications.warn(
            getGame().i18n.format("DS4.WarningControlledActorDoesNotHaveItem", {
                actorName: actor.name,
                actorId: actor.id,
                itemId,
            }),
        );
    }

    return item.roll({ speaker: { token } }).catch((e) => notifications.error(e, { log: true }));
}