import { system, world, EquipmentSlot, ItemStack, Block, BlockPermutation } from "@minecraft/server";
import { onRemoveUpgrader } from "../entities/gauntlet_upgrader.js";
const validTags = {
    unstableEnergyOre: [
        "minecraft:iron_tier",
        "minecraft:diamond_tier",
        "minecraft:netherite_tier"
    ]
}
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

// Register a custom component before the world is loaded
world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent("oct_eg:gauntlet_crafter", {
        beforeOnPlayerPlace(event) {
            event.cancel = !checkEmptySpaceAboveLocation(event.block);
            // cancel = !checkEmptySpaceAboveLocation(block);
        },
        onPlace({ block, dimension }) {
            placeGauntletUpgrader(block, dimension);
        },
        onPlayerDestroy({ block, dimension }) {
            removeGauntletUpgrader(block, dimension);
        }
    });
    blockComponentRegistry.registerCustomComponent("oct_eg:unstable_energy_ore_loot", {
        onPlayerDestroy({ block, dimension, player }) {
            // Check the tool in the player's hand
            const equippable = player?.getComponent("minecraft:equippable");
            if (!equippable) return; // Exit if the player or its equipment are undefined

            const itemStack = equippable.getEquipment(EquipmentSlot.Mainhand);
            if (!itemStack?.hasTag("minecraft:is_pickaxe")) return; // Exit if the player isn't holding a pickaxe
            const itemTags = itemStack?.getTags() ?? [];
            if (!validTags.unstableEnergyOre.some(tag => itemTags.includes(tag))) return; // Exit if the player isn't holding a suitable pickaxe

            // Specify enchantments
            const enchantable = itemStack.getComponent("minecraft:enchantable");
            const silkTouch = enchantable?.getEnchantment("silk_touch");
            if (silkTouch) return; // Exit if the pickaxe has the Silk Touch enchantment


            // Spawn the loot
            const spawnlock = block.center();
            const dropAmount = getFortunedOreAmount(enchantable, 1);
            const droppedItem = new ItemStack("oct_eg:unstable_energy", dropAmount);
            dimension.spawnItem(droppedItem, spawnlock);

            // Spawn the XP orbs
            xpReward(dimension, spawnlock, 2, 5);
        },
    });
});

function checkEmptySpaceAboveLocation(block) {
    try {
        const blockAbove = block.offset({ x: 0, y: 1, z: 0 });
        if (blockAbove.isAir) return true
        if (blockAbove.isLiquid) return true
        return false
    } catch (e) {
        return false
    }
}

function placeGauntletUpgrader(block, dimension) {
    try {
        // Get the spawn location
        const spawnLocation = block.offset({ x: 0, y: 1, z: 0 })?.bottomCenter() || null;
        if (!spawnLocation) return;

        // Spawn the upgrader
        const upgrader = dimension.spawnEntity("oct_eg:gauntlet_upgrader", spawnLocation);
        if (!upgrader) return;

        //world.sendMessage(`Gauntlet Upgrader §2placed§r at ${spawnLocation.x}, ${spawnLocation.y}, ${spawnLocation.z}`);
    }
    catch (e) {
        return;
    }
}

function removeGauntletUpgrader(block, dimension) {
    try {
        const aboveLocation = block.offset({ x: 0, y: 1, z: 0 })?.bottomCenter() || null;
        if (!aboveLocation) return;

        const upgraders = dimension.getEntities({
            location: aboveLocation,
            type: "oct_eg:gauntlet_upgrader",
            maxDistance: 0.5
        });
        for (const upgrader of upgraders) {
            if (upgrader?.isValid()) { onRemoveUpgrader(upgrader) };
        }
    }
    catch (e) {
        return;
    }
}

function xpReward(dimension, spawnlock, min, max) {
    // Spawn the XP orbs
    const xpAmount = randomInt(min, max);

    for (let i = 0; i < xpAmount; i++) {
        dimension.spawnEntity("minecraft:xp_orb", spawnlock);
    }
}
function getFortunedOreAmount(enchantableComponent, defaultAmount) {
    if (!enchantableComponent) return defaultAmount;
    const fortune = enchantableComponent?.getEnchantment("fortune")?.level || 0;

    let dropMultiplier = 1;
    if (fortune > 0) {
        const baseChance = 2 / (fortune + 2);
        if (Math.random() >= baseChance) {
            // Determine bonus drop based on Fortune level
            const roll = Math.random();
            if (fortune === 1) {
                dropMultiplier = roll < 1 / 3 ? 2 : 1;
            } else if (fortune === 2) {
                dropMultiplier = roll < 1 / 4 ? 3 : roll < 2 / 4 ? 2 : 1;
            } else if (fortune >= 3) {
                dropMultiplier = roll < 1 / 5 ? 4 : roll < 2 / 5 ? 3 : roll < 3 / 5 ? 2 : 1;
            }
        }
    }

    return defaultAmount * dropMultiplier;
}


world.afterEvents.pistonActivate.subscribe(event => {
    const { dimension, isExpanding, piston, block: pistonBlock } = event;

    const offset = [
        { x: 0, y: -1, z: 0 },
        { x: 0, y: 1, z: 0 },
        { x: 0, y: 0, z: 1 },
        { x: 0, y: 0, z: -1 },
        { x: 1, y: 0, z: 0 },
        { x: -1, y: 0, z: 0 }
    ][pistonBlock.permutation.getState('facing_direction')];

    if (!isExpanding) { offset.x *= -1; offset.y *= -1; offset.z *= -1 }

    piston.getAttachedBlocks().forEach(async block => {
        const oldLocation = block.location;
        const newLocation = { x: oldLocation.x + offset.x, y: oldLocation.y + offset.y, z: oldLocation.z + offset.z };

        const newBlock = dimension.getBlock(newLocation)

        const upgraders = dimension.getEntities({
            location: {
                x: oldLocation.x,
                y: oldLocation.y + 1,
                z: oldLocation.z
            },
            type: "oct_eg:gauntlet_upgrader",
            maxDistance: 0.5
        });
        for (const upgrader of upgraders) {
            if (upgrader?.isValid()) { onRemoveUpgrader(upgrader) };
            //world.sendMessage(`Upgrader §cremoved§r`);
        }

        await system.waitTicks(3);

        if (newBlock.typeId !== "oct_eg:gauntlet_crafter") return;

        //world.sendMessage(newBlock.typeId) // Logs not minecraft:moving_block
        removeGauntletUpgrader(newBlock, dimension);
        dimension.spawnItem(new ItemStack("oct_eg:gauntlet_crafter", 1), newBlock.center());
        newBlock.setPermutation(BlockPermutation.resolve("minecraft:air"));
    })
})