import { world, Player, ItemStack } from "@minecraft/server";
import { placeCircusTent } from "../utils/utils";
import { clowns } from "../entities/circus_wheel";
import { FormCancelationReason, MessageFormData } from "@minecraft/server-ui";

const spawnItems = new Map([
    ["px_hc:clown_spawn", 1],
    ["px_hc:ringmaster_spawn", 2],
    ["px_hc:juggler_spawn", 3],
    ["px_hc:illusionist_spawn", 4],
    ["px_hc:strongman_spawn", 5],
    ["px_hc:harley_quinn_spawn", 6],
    ["px_hc:butcher_spawn", 7],
    ["px_hc:pyro_spawn", 8],
    ["px_hc:stilt_walker_spawn", 9],
    ["px_hc:jester_spawn", 10],
]);

world.afterEvents.itemUse.subscribe((event) => {
    const { itemStack: item, source: player } = event;

    if (spawnItems.has(item.typeId)) {
        spawnMobMessage(player, item);
    }
});

/**
 *
 * @param {Player} player
 * @param {ItemStack} item
 */
function spawnMobMessage(player, item) {
    const UI = new MessageFormData();

    const { dimension } = player;

    const direction = player.getViewDirection();

    const spawnLocation = player.getBlockFromViewDirection({ maxDistance: 6 })?.block.location ?? {
        x: player.location.x + direction.x * 6,
        y: player.location.y,
        z: player.location.z + direction.z * 6,
    };

    const name = new String(player.name);

    const clownNumber = spawnItems.get(item.typeId);

    const clown = clowns.get(clownNumber);

    UI.title("");
    UI.body("Are you sure you want to spawn the mob now?");
    UI.button1("Yes");
    UI.button2("No");

    UI.show(player).then((response) => {
        const selection = response.selection;

        if (
            response.canceled ||
            response.cancelationReason == FormCancelationReason.UserBusy ||
            response.cancelationReason == FormCancelationReason.UserClosed
        ) {
            return;
        }

        if (selection == 0) {
            dimension.spawnEntity(clown, {
                x: spawnLocation.x,
                y: spawnLocation.y + 1,
                z: spawnLocation.z,
            });
            player.runCommand(`clear ${name} ${item.typeId} 0 ${1}`);
        } else return;
    });
}
