import { system, world, Direction, BlockPermutation } from "@minecraft/server";

const ammoBoxMapping = {
    "ttav:tank_flare_gun": "ttav:flare_ammo_box",
    "ttav:tank_main_gun": "ttav:main_ammo_box", 
    "ttav:tank_sub_gun": "ttav:sub_ammo_box"
};

class AmmoBoxComponent {
    constructor() {
        this.onPlayerInteract = this.onPlayerInteract.bind(this);
    }

    onPlayerInteract(event) {
        const { block, player } = event;
        const heldItem = player.getComponent("minecraft:equippable").getEquipment("Mainhand");
        
        
        if (block.typeId === "ttav:main_ammo_box" && heldItem?.typeId === "ttav:tank_main_gun") {
            const currentPermutation = block.permutation;
            const currentVariant = currentPermutation.getState("ttav:variant") || 0;
            const newVariant = currentVariant >= 3 ? 0 : currentVariant + 1;
            
            const newPermutation = BlockPermutation.resolve("ttav:main_ammo_box", {
                ...currentPermutation.getAllStates(),
                "ttav:variant": newVariant
            });
            
            block.setPermutation(newPermutation);
            player.runCommand(`playsound random.click @s ~ ~ ~`);
            return;
        }
        
        
        if (heldItem && (
            heldItem.typeId === "ttav:tank_flare_gun" ||
            heldItem.typeId === "ttav:tank_main_gun" ||
            heldItem.typeId === "ttav:tank_sub_gun"
        )) {
            return;
        }

        
        if (!["ttav:flare_ammo_box", "ttav:main_ammo_box", "ttav:sub_ammo_box"].includes(block.typeId)) {
            return;
        }

        const blockToItemMapping = Object.fromEntries(
            Object.entries(ammoBoxMapping).map(([item, block]) => [block, item])
        );

        const itemToGive = blockToItemMapping[block.typeId];
        if (itemToGive) {
            system.run(() => {
                try {
                    const blockLocation = block.location;
                    const { x, y, z } = blockLocation;
                    player.runCommand(`give @s ${itemToGive}`);
                    player.runCommand(`setblock ${x} ${y} ${z} air`);
                    player.playSound("random.pop", { pitch: 1.0, volume: 1.0 });
                } catch (error) {
                    console.warn("处理弹药箱交互时出错:", error);
                }
            });
        }
    }
}

const ammoBoxComponent = new AmmoBoxComponent();

world.beforeEvents.worldInitialize.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent(
        "ttav:flare_ammo_box",
        ammoBoxComponent
    );
    initEvent.blockComponentRegistry.registerCustomComponent(
        "ttav:main_ammo_box",
        ammoBoxComponent
    );
    initEvent.blockComponentRegistry.registerCustomComponent(
        "ttav:sub_ammo_box",
        ammoBoxComponent
    );
});

world.beforeEvents.itemUseOn.subscribe((event) => {
    const item = event.itemStack;
    const faceBlock = event.block;
    const player = event.source;

    
    if (item.typeId === "ttav:tank_main_gun" && 
        faceBlock.typeId === "ttav:main_ammo_box" && 
        !player.isSneaking) {
        return;
    }

    if (!Object.keys(ammoBoxMapping).includes(item.typeId)) {
        return;
    }

    system.run(() => {
        try {
            const newBlock = getNewBlock(faceBlock, event.blockFace);

            if (newBlock.typeId !== "minecraft:air") {
                return;
            }

            const blockToPlace = ammoBoxMapping[item.typeId];
            const rotation = player.getRotation();
            const yaw = rotation.y;
            let cardinalDirection;

            if (yaw >= -45 && yaw < 45) {
                cardinalDirection = "south";
            } else if (yaw >= 45 && yaw < 135) {
                cardinalDirection = "west";
            } else if (yaw >= 135 || yaw < -135) {
                cardinalDirection = "north";
            } else {
                cardinalDirection = "east";
            }

            const blockPermutation = BlockPermutation.resolve(blockToPlace, {
                "minecraft:cardinal_direction": cardinalDirection
            });

            newBlock.setPermutation(blockPermutation);

            const equippable = player.getComponent("minecraft:equippable");
            const currentItem = event.itemStack;

            if (currentItem.amount > 1) {
                currentItem.amount--;
                equippable.setEquipment("Mainhand", currentItem);
            } else {
                equippable.setEquipment("Mainhand", undefined);
            }
        } catch (error) {
            console.warn("放置弹药箱时出错:", error);
        }
    });
});

function getNewBlock(block, face) {
    switch (face) {
        case Direction.Up:
            return block.above();
        case Direction.Down:
            return block.below();
        case Direction.North:
            return block.north();
        case Direction.South:
            return block.south();
        case Direction.East:
            return block.east();
        case Direction.West:
            return block.west();
        default:
            return null;
    }
}

export { ammoBoxComponent };
