import { Entity, EntityDamageCause, ItemStack, Player, system, world } from "@minecraft/server";
import { Entities } from "./Entities";
import { getRandomBetween, movePlayerAway } from "../utils/utils";

world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
    const { entity, eventId } = event;

    if (entity.typeId == Entities.clown_box) {
        switch (eventId) {
            case "clown:move_player_away": {
                movePlayerAway(entity, 1.7);

                break;
            }
        }
    }
});
const drops = new Map([
    [
        1,
        {
            item: "minecraft:rotten_flesh",
            count: 1,
        },
    ],
    [
        2,
        {
            item: "minecraft:diamond",
            count: 2,
        },
    ],
    [
        3,
        {
            item: "minecraft:iron_ingot",
            count: 10,
        },
    ],
    [
        4,
        {
            item: "minecraft:gold_ingot",
            count: 10,
        },
    ],
]);

const events = new Map([
    [
        1,
        {
            exec: explode,
        },
    ],
    [
        2,
        {
            exec: lightning,
        },
    ],
]);

world.afterEvents.entityDie.subscribe((event) => {
    const { deadEntity, damageSource } = event;

    if (deadEntity.typeId == Entities.clown_box) {
        const random = getRandomBetween(1, 6);

        if (random < drops.size) {
            const item = new ItemStack(drops.get(random).item, drops.get(random).count);
            deadEntity.dimension.spawnItem(item, deadEntity.location);
        } else {
            const randomEvent = getRandomBetween(1, 1);

            events.get(randomEvent).exec(deadEntity, damageSource);
        }
    }
});

/**
 *
 * @param {Entity} deadEntity
 * @param {Entity} damageSource
 */
function explode(deadEntity, damageSource) {
    const { dimension, location } = deadEntity;

    dimension.createExplosion(location, 4, { breaksBlocks: false });
}
